I would like to mock an interface that's passed in as the main argument to a function, but the method is complicated, and as a result I don't want to have to specify defaults or exact behavior for every test. I'd like to specify defaults in a Setup method, and override specific parts of that in each test as required.
I.e.:
public interface IOptions
{
string Something { get; }
}
[TestFixture]
public class Tester
{
MockRepository mocks;
IOptions someOptions;
string expectedXml;
[Setup]
public void Setup()
{
mocks = new MockRepository();
someOptions = mocks.DynamicMock<IOptions>();
//Something that would go here.
// I.e. SetupResult.For(someOptions.Something).Return("default");
}
[Teardown]
public void Teardown()
{
mocks.ReplayAll();
using (var ms = new MemoryStream())
{
var unitUnderTest = new SomeOptionsWriter(ms);
unitUnderTest.Write(someOptions);
Assert.AreEqual(expectedXml, Encoding.Utf8.GetString(ms.ToArray()));
}
mocks.VerifyAll();
}
[Test]
public void SomeTest()
{
expectedXml = "<root><default></default></root>";
//Relies on default behavior
}
[Test]
public void SomeTest2()
{
expectedXml = "<root><sub></sub></root>";
Expect.Call(someOptions.Something).Return("sub");
}
}
How can I accomplish this using Rhino Mocks?
In order to completely answer your question, I have to leap off @Patrick Steele's answer. Use the AAA setup. Declare your default stubs in the SetUp method and then override those stubs in specific Test methods. You won't be able to remove existing stubs unless you re-instantiate the object however.
The last stub added for a given function will override the previous.
someOptions.Stub(o => o.Something).Return("default");
someOptions.Stub(o => o.Something).Return("override");
The above stub in the example will return "override" when called.