验证基类中的方法调用,该类使用Moq获取委托参数

时间:2014-01-03 21:45:42

标签: c# unit-testing delegates mocking moq

我试图测试一个方法被调用,并且该方法存在于被测试类的基类中。

当我使用简单的字符串参数运行以下示例时,它可以工作,但是当存在委托参数时,测试失败。

我创建了以下示例来演示问题。如果您在SomeMethod和测试中取出委托参数,测试将通过。

代码失败:

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

1 个答案:

答案 0 :(得分:5)

如果我将测试更改为跟随它通过。请参阅我将() => 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);