2009-02-09

Rhino Mocks, returning a different result every time

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


This test case shows a problem I was having. The return value of the stubbed CreateFileStream method isn't calculated each time it is called, it is calculated once at the point you defined the stub method and then returned for every subsequent call. The problem with this is that my real test needed to call CreateFileStream twice and get two different streams, the test was failing because the method being tested disposes of the stream it uses; this was resulting in an ObjectDisposedException in my test.

The correct way to implement this is to override the return value using WhenExecuted()

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

No comments: