Marcelo Oliveira
Marcelo Oliveira

Reputation: 673

How can I assert that a method of a specific class was called before another method of another class?

Here goes an example of what I have:

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

In this sample I just check if they were called, no mather the sequence...

Im considering to setup a callback in those methods that add some kind of sequence control in the test class...

edit: I'm using the moq lib: http://code.google.com/p/moq/

Upvotes: 3

Views: 215

Answers (3)

Igor Zevaka
Igor Zevaka

Reputation: 76550

Alternate solution, verify the first method was called when the second one is being called:

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

Upvotes: 1

Luke Hutton
Luke Hutton

Reputation: 10722

Rhino Mocks supports orders in the mocking, see http://www.ayende.com/Wiki/Rhino+Mocks+Ordered+and+Unordered.ashx

Or Moq Sequences perhaps, http://dpwhelan.com/blog/software-development/moq-sequences/

See here for a similar question on this, How to test method call order with Moq

Upvotes: 2

C. Ross
C. Ross

Reputation: 31848

Record a time stamp in each of your mocks, and compare them.

[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");
}

Upvotes: 0

Related Questions