我正在尝试测试是否调用了一个方法,并且该方法存在于被测类的基类中。
当我使用一个简单的字符串参数运行下面的示例时,它可以工作,但是当有一个委托(delegate)参数时,测试失败。
我创建了以下示例来演示该问题。如果在SomeMethod
中取出delegate参数,在测试中,测试就会通过。
失败代码:
public abstract class BaseClass
{
public virtual void SomeMethod(string someString, Func<bool> function)
{
//do something
}
}
public class DerivedClass : BaseClass
{
public void DoSomething()
{
SomeMethod("foo", () => true);
}
}
[TestClass]
public class Tests
{
[TestMethod]
public void TestMethod1()
{
var test = new Mock<DerivedClass>();
test.Object.DoSomething();
test.Verify(x => x.SomeMethod("foo", () => true), Times.AtLeastOnce);
}
}
传递代码:
public abstract class BaseClass
{
public virtual void SomeMethod(string someString)
{
//do something
}
}
public class DerivedClass : BaseClass
{
public void DoSomething()
{
SomeMethod("foo");
}
}
[TestClass]
public class Tests
{
[TestMethod]
public void TestMethod1()
{
var test = new Mock<DerivedClass>();
test.Object.DoSomething();
test.Verify(x => x.SomeMethod("foo"), Times.AtLeastOnce);
}
}
测试失败的错误信息:
Expected invocation on the mock at least once, but was never performed: x => x.SomeMethod("foo", () => True)
No setups configured.
Performed invocations:
BaseClass.SomeMethod("foo", System.Func1[System.Boolean])`
整个错误信息:
Test method UnitTestProject1.Tests.TestMethod1 threw exception:
Moq.MockException:
Expected invocation on the mock at least once, but was never performed: x => x.SomeMethod("foo", () => True)
No setups configured.
Performed invocations:
BaseClass.SomeMethod("foo", System.Func`1[System.Boolean])
at Moq.Mock.ThrowVerifyException(MethodCall expected, IEnumerable`1 setups, IEnumerable`1 actualCalls, Expression expression, Times times, Int32 callCount)
at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times)
at Moq.Mock.Verify(Mock`1 mock, Expression`1 expression, Times times, String failMessage)
at Moq.Mock`1.Verify(Expression`1 expression, Times times)
at Moq.Mock`1.Verify(Expression`1 expression, Func`1 times)
at UnitTestProject1.Tests.TestMethod1() in UnitTest1.cs: line 16
最佳答案
如果我将测试更改为以下,它就会通过。看我改了() => true
至 It.IsAny<Func<bool>>()
这意味着它可以用任何 Func 调用。你关心它是不是() => true
?
var test = new Mock<DerivedClass>();
test.Object.DoSomething();
test.Verify(x => x.SomeMethod("foo", It.IsAny<Func<bool>>()), Times.AtLeastOnce);
关于c# - 使用 Moq 验证采用委托(delegate)参数的基类中的方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20913236/