user485553
user485553

Reputation: 301

Unit test, Rhino, The art of unit testing

I've started to read "The art of unit testing" and I'm trying to implement this piece of code:

[Test]
public void ReturnResultsFromMock()
{
    MockRepository mocks = new MockRepository();
    IGetResults resultGetter = mocks.DynamicMock<IGetResults>();
    using(mocks.Record())
     {
        resultGetter.GetSomeNumber("a");//#1
        LastCall.Return(1);
        resultGetter.GetSomeNumber("a");//#2 how it should work?
        LastCall.Return(2);
        resultGetter.GetSomeNumber("b");
        LastCall.Return(3);
    }
    int result = resultGetter.GetSomeNumber("b");
    Assert.AreEqual(3, result);
    int result2 = resultGetter.GetSomeNumber("a");
    Assert.AreEqual(1, result2);
    int result3 = resultGetter.GetSomeNumber("a");
    Assert.AreEqual(2, result3);
}

I get this error message after running my test AOUT.Loga.Tests.LogAnalyzerTest.ReturnResultsFromMock: Expected: 2 But was: 1

Upvotes: 1

Views: 232

Answers (2)

Amittai Shapira
Amittai Shapira

Reputation: 3827

You may try using the simpler Rhino Mocks AAA syntax, your code will look something like this (take a look also at this question):

    // Arrange
    var resultGetter = MockRepository.GenerateMock<IGetResults>;
    resultGetter.Expect(x => x.GetSomeNumber("b")).Return(3);
    resultGetter.Expect(x => x.GetSomeNumber("a")).Return(1).Repeat.Once();
    resultGetter.Expect(x => x.GetSomeNumber("b")).Return(2).Repeat.Once();

    // Act
    int result = resultGetter.GetSomeNumber("b");
    // Assert
    Assert.AreEqual(3, result);
    // Act
    int result2 = resultGetter.GetSomeNumber("a");
    // Assert
    Assert.AreEqual(1, result2);
    // Act
    int result3 = resultGetter.GetSomeNumber("a");
    // Assert
    Assert.AreEqual(2, result3);

Upvotes: 0

Akim
Akim

Reputation: 8669

Looks like you try to implement ordered sequence of calls (see details here):

  • First you call GetSomeNumber("a") should returns 1
  • Then call GetSomeNumber("a") again, result will be 2
  • And only then GetSomeNumber("b"), result will be 3

Is so, try to replace using(mocks.Record()) with using(mocks.Ordered()). But, this will work only in this sequence of calls

At your example, you are using using(mocks.Record()), so every call to GetSomeNumber("a") will return 2 acording to your configuration. You're override first GetSomeNumber("a") by second one. Here are correct assumptions:

int result = resultGetter.GetSomeNumber("b");
Assert.AreEqual(3, result);
int result2 = resultGetter.GetSomeNumber("a");
Assert.AreEqual(2, result2); // every call to GetSomeNumber("a") will returns 2
int result3 = resultGetter.GetSomeNumber("a");
Assert.AreEqual(2, result3);

Upvotes: 2

Related Questions