Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rhino Mocks, returning a different result each time stubbed method is executed

Tags:

c#

rhino-mocks

In this example the .Stub returns a new memory stream. The same memory stream is returned both times. What I want is a new memory stream every time. My question is, how do I change the .Stub in order to make this test pass?

[TestMethod]
public void Meh()
{
    var mockFileSystem = MockRepository.GenerateMock<IFileSystemService>();
    mockFileSystem.Stub(fs => fs.CreateFileStream(null, FileMode.Append, FileAccess.Write, FileShare.None))
        .IgnoreArguments()
        .Return(new MemoryStream());

    var result1 = mockFileSystem.CreateFileStream(null, FileMode.Append, FileAccess.Write, FileShare.None);
    var result2 = mockFileSystem.CreateFileStream(null, FileMode.Append, FileAccess.Write, FileShare.None);
    Assert.AreNotSame(result1, result2);
}
like image 900
Peter Morris Avatar asked Feb 07 '09 20:02

Peter Morris


1 Answers

The trick is to use WhenCalled to replace the previous Return operation:

[TestMethod]
public void Meh()
{
    var mockFileSystem = MockRepository.GenerateMock<IFileSystemService>();
    mockFileSystem.Stub(fs => fs.CreateFileStream(null, FileMode.Append, FileAccess.Write, FileShare.None))
        .IgnoreArguments()
        .Return(null) 

        //*****The return value is replaced in the next line!
        .WhenCalled(invocation => invocation.ReturnValue = new MemoryStream());

    var result1 = mockFileSystem.CreateFileStream(null, FileMode.Append, FileAccess.Write, FileShare.None);
    var result2 = mockFileSystem.CreateFileStream(null, FileMode.Append, FileAccess.Write, FileShare.None);
    Assert.AreNotSame(result1, result2);
}
like image 113
Peter Morris Avatar answered Oct 20 '22 17:10

Peter Morris