我定义了以下mock(使用Moq)。
mockSqlConnection.Setup(x => x.Query<Address>(
It.IsAny<string>(),
null,
null,
true,
null,
null))
.Returns(new List<Address>
{
new Address()
});
以及以下验证
mockSqlConnection.Verify(x => x.Query<Address>(
It.IsAny<string>(),
null,
null,
true,
null,
null), Times.Once);
这两个都过去了!太好了!
然后我有这个代码执行实际调用..
var result = sqlConnection.Query<Address>(.....);
并返回NULL
。
我无法弄清楚为什么总是返回null,当我在安装程序中定义时,返回一个包含一个项目的列表。
当我测试运行我的测试时,这是有效的。 但是,当我Test-DebugRun ..这是所有这些错误发生的地方! :(
如果我强迫Moq出错(即使用inccorect验证金额:)我期待一次,所以我会说Never
..这就是我在HARDCODE args中所说的..或者使用It.IsAny<T>
个..
Moq.MockException
Expected invocation on the mock should never have been performed, but was 1 times: x => x.Query<Address>(It.IsAny<String>(), null, null, True, null, null)
Configured setups:
x => x.Query<Address>(It.IsAny<String>(), null, null, True, null, null), Times.Once
Performed invocations:
IDbExecutor.Open()
IDbExecutor.Query(" -- code snipped --", null, null, True, null, null)
IDbExecutor.Close()
IDisposable.Dispose()
Moq.MockException
Expected invocation on the mock should never have been performed, but was 1 times: x => x.Query<Address>(It.IsAny<String>(), It.IsAny<Object>(), It.IsAny<IDbTransaction>(), It.IsAny<Boolean>(), It.IsAny<Nullable`1>(), It.IsAny<Nullable`1>())
Configured setups:
x => x.Query<Address>(It.IsAny<String>(), null, null, True, null, null), Times.Never
x => x.Query<Address>(It.IsAny<String>(), It.IsAny<Object>(), It.IsAny<IDbTransaction>(), It.IsAny<Boolean>(), It.IsAny<Nullable`1>(), It.IsAny<Nullable`1>()), Times.Once
Performed invocations:
IDbExecutor.Open()
IDbExecutor.Query(" -- sql query snipped --", null, null, True, null, null)
IDbExecutor.Close()
IDisposable.Dispose()
我不理解:(
答案 0 :(得分:1)
原因是因为某些参数是硬编码的。如果您希望无论参数如何都返回new Address()
,请尝试以下操作:
It.IsAny<T>()
的参数允许任何值。如果参数是特定值,则Setup
将按照您的定义执行该特定值。
mockSqlConnection.Setup(x => x.Query<Address>(
It.IsAny<string>(),
It.IsAny<TheType>(),
It.IsAny<TheType>(),
It.IsAny<bool>(),
It.IsAny<TheType>(),
It.IsAny<TheType>()))
.Returns(new List<Address>
{
new Address()
});
您的Verify
还需要使用It.IsAny<T>()
才能正确传递:
mockSqlConnection.Verify(x => x.Query<Address>(
It.IsAny<string>(),
It.IsAny<TheType>(),
It.IsAny<TheType>(),
It.IsAny<bool>(),
It.IsAny<TheType>(),
It.IsAny<TheType>(), Times.Once);