Reputation: 2788
I am experiencing an issue with Moq in my unit testing and I am not sure where I am going wrong. I have a method in my interface with like this:
void WriteToRegistryKey (String key, Object value);
and I am unit testing it like this:
var testRegistry = new Mock<IRegistry>();
testRegistry.Setup(x => x.WriteToRegistryKey(It.IsAny<string>(), It.IsAny<int>()));
Utility testUtility = new ConfigUtil(testRegistry.Object);
testUtility.UpdateRegistry();
testRegistry.Verify(x => x.WriteToRegistryKey("MaxNumLogFiles", 10));
Under the hood when I call testUtility.UpdateRegistry() it calls my WriteToRegistryKey I want to test that WriteToRegistryKey method passing in the correct values.
However I receive this when I run the test:
Moq.MockException :
Expected invocation on the mock at least once, but was never performed: x => x.WriteToRegistryKey("MaxNumLogFiles", (Object)10)
Configured setups:
x => x.WriteToRegistryKey(It.IsAny<String>(), It.IsAny<Int32>()), Times.Never
Performed invocations:
IRegistry.WriteToRegistryKey("MaxNumLogFiles", 10)
If I change my testRegistry.Verify to:
testRegistry.Verify(x => x.WriteToRegistryKey("MaxNumLogFiles", It.IsAny<object>()));
it works, so the issue seems to be around the second parameter the WriteToRegistryKey method takes, and the difference between int and object, but I cant seem to figure it out.
Thanks for all help!
Upvotes: 1
Views: 1363
Reputation: 256
It would be helpful to see the body of implementation of testUtility.UpdateRegistry();
how the .WriteToRegistryKey
method is called there.
However:
I would remove the line where you setup the testRegistry
mock:
testRegistry.Setup(x => x.WriteToRegistryKey(It.IsAny<string>(), It.IsAny<int>()));
Because, you want to test it, if it was called with correct arguments or not. There is no reason to setup that with Moq.
and if your test passes with
testRegistry.Verify(x => x.WriteToRegistryKey("MaxNumLogFiles", It.IsAny<object>()));
It could mean two things:
It.IsAny<string>(), It.IsAny<int>()
When you use It.IsAny<type>()
it could be also null
.
Upvotes: 3