1

我在单元测试中遇到了起订量问题,我不确定我哪里出错了。我的界面中有一个方法,如下所示:

void WriteToRegistryKey (String key, Object value);

我正在像这样对它进行单元测试:

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));

当我调用 testUtility.UpdateRegistry() 时,它会调用我的 WriteToRegistryKey 我想测试传递正确值的 WriteToRegistryKey 方法。

但是,当我运行测试时我收到了这个:

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)

如果我将 testRegistry.Verify 更改为:

testRegistry.Verify(x => x.WriteToRegistryKey("MaxNumLogFiles", It.IsAny<object>()));

它有效,因此问题似乎与 WriteToRegistryKey 方法采用的第二个参数以及 int 和 object 之间的区别有关,但我似乎无法弄清楚。

感谢大家的帮助!

4

1 回答 1

3

testUtility.UpdateRegistry();查看如何在.WriteToRegistryKey那里调用该方法的实现主体会很有帮助。

但是:我会删除您设置testRegistry模拟的行:
testRegistry.Setup(x => x.WriteToRegistryKey(It.IsAny<string>(), It.IsAny<int>())); 因为,您想测试它,是否使用正确的参数调用它。没有理由使用 Moq 进行设置。

如果你的测试通过 testRegistry.Verify(x => x.WriteToRegistryKey("MaxNumLogFiles", It.IsAny<object>()));

这可能意味着两件事:

  1. 您的 WriteToRegistryKey 方法是用10以外的值调用的 - UpdateRegistry 方法中的错误
  2. 或者它是空的,因为你设置它:

It.IsAny<string>(), It.IsAny<int>()

使用It.IsAny<type>()时也可以null

于 2012-08-02T19:23:52.153 回答