如何断言在另一个类的另一个方法之前调用特定类的方法?

时间:2011-05-11 16:39:10

标签: .net nunit moq

以下是我所拥有的一个例子:

public class ClassToBeTestedTest
{
    private Mock<IAService> aService;
    private Mock<IAnotherService> anotherService;
    private ClassToBeTested testedClass;

    [SetUp]
    public void setup()
    {
        aService = new Mock<IAService>();
        anotherService = new Mock<IAnotherService>();
        testedClass = new ClassToBeTested(aService.Object, anotherService.Object);
    }

    [Test]
    public void ShouldCallAServiceMethodBeforeAnotherService()
    {
        testedClass.Run();
        aService.Verify(x=>x.AMethod(), Times.Once());
        anotherService.Verify(x=>x.AnotherMethod(), Times.Once());
    }
}

在这个样本中,我只是检查它们是否被调用,而不是序列......

我正考虑在那些在测试类中添加某种序列控制的方法中设置一个回调...

编辑:我正在使用moq lib:http://code.google.com/p/moq/

3 个答案:

答案 0 :(得分:2)

Rhino Mocks支持模拟中的订单,请参阅http://www.ayende.com/Wiki/Rhino+Mocks+Ordered+and+Unordered.ashx

Or Moq序列也许,http://dpwhelan.com/blog/software-development/moq-sequences/

请点击此处查看类似的问题,How to test method call order with Moq

答案 1 :(得分:1)

替代解决方案,验证在调用第二个方法时调用第一个方法:

public class ClassToBeTestedTest
{
    private Mock<IAService> aService;
    private Mock<IAnotherService> anotherService;
    private ClassToBeTested testedClass;

    [SetUp]
    public void setup()
    {
        aService = new Mock<IAService>();
        anotherService = new Mock<IAnotherService>();
        testedClass = new ClassToBeTested(aService.Object, anotherService.Object);
    }

    [Test]
    public void ShouldCallAServiceMethodBeforeAnotherService()
    {
        //Arrange
        anotherService.Setup(x=>x.AnotherMethod()).Callback(()=>{
            //Assert
            aService.Verify(x=>x.AMethod(), Times.Once());
        }).Verifyable();

        //Act
        testedClass.Run();
        //Assert
        anotherService.Verify();
    }
}

答案 2 :(得分:0)

在每个模拟中记录时间戳,并进行比较。

[Test]
public void ShouldCallAServiceMethodBeforeAnotherService()
{
    testedClass.Run();
    //Not sure about your mocking library but you should get the idea
    Assert(aService.AMethod.FirstExecutionTime 
        < anotherService.AnotherMethod.FirstExecutionTime, 
        "Second method executed before first");
}