1

My mock test is throwing a KeyNotFoundException:

[Fact]
public void MockAssembly_GetTypes_ReturnsMockedTypes()
{
    var mockAssembly = new Mock<Assembly>();

    mockAssembly.Setup(a => a.GetTypes()).Returns(new Type[] { typeof(MyClass) });
    var mockAssemblyObject = mockAssembly.Object;

    var assemblyDictionary = new Dictionary<Assembly, HashSet<Type>>();
    if (!assemblyDictionary.TryGetValue(mockAssemblyObject, out var types))
    {
        types = new HashSet<Type>(mockAssemblyObject.GetTypes());
        assemblyDictionary[mockAssemblyObject] = types;
    }

    Assert.Contains(mockAssemblyObject, assemblyDictionary.Keys);
    Assert.Single(assemblyDictionary[mockAssemblyObject]);
}

System.Collections.Generic.KeyNotFoundException: The given key '' was not present in the dictionary.

On the line Assert.Single(assemblyDictionary[mockAssemblyObject]);

Even mocking GetHashCode doesn't help - it still tries to use an empty key.

Why is this happening?

Edit:

Further testing shows if I call assemblyDictionary.TryGetValue(mockAssemblyObject, out var myTypes); even immediately after I add using assemblyDictionary.Add(mockAssemblyObject, types) the result is false and null.

6
  • Is the key in the database? You created a new dictionary. Where did you insert values into the database? Commented Nov 26, 2023 at 14:40
  • @jdweng assemblyDictionary[mockAssemblyObject] = types; I believe does this. Commented Nov 26, 2023 at 14:43
  • Try using assemblyDictionary.Add(... Commented Nov 26, 2023 at 15:05
  • @Eldar same exception. When I debug I can see the dictionary contains the added mocked object. Even when I try another TryGetValue it fails. See my edit. Commented Nov 26, 2023 at 15:09
  • A row of a Dictionary contains a KEY and a VALUE. You mockAssemblyObject does not have a KEY and VALUE. Commented Nov 26, 2023 at 15:12

1 Answer 1

2

Set CallBase to true:

var mockAssembly = new Mock<Assembly>() { CallBase = true };

Both Equals and GetHashCode are also virtual methods, and unless you set CallBase to true, Moq will also override these methods with 'mock' implementations.

It's not quite obvious that this fixes the problem, but in my repro of the OP, it does. The test now passes.

Sign up to request clarification or add additional context in comments.

1 Comment

Can verify this fixes the problem! Thank you for the answer this was very puzzling for me :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.