RhinoMock to return different value based on method parameter

How do you return different values based on different parameter in a mocked object using RhinoMock?

Maybe there are other ways of doing the same thing. These are the two methods that i know.

Lets say i have the following interface that i wanna mock.

public interface ITest
{
int Test(string data);
}


[TestMethod] // Method #1
public void ExpectConditionalMethodInputParameter()
{
var mock = new MockRepository();
var subject = mock.DynamicMock();
int result;

With.Mocks(mock).Expecting
(
delegate
{
Expect.Call(subject.Test(Arg.Is.Equal("1"))).Return(100).Repeat.Any(); // Set expectation input parameter1
Expect.Call(subject.Test(Arg.Is.Equal("2"))).Return(200).Repeat.Any(); // Set expectation input parameter2
}
).Verify(
delegate
{
result = subject.Test("2"); // Returns 200 if parameter is 2, return 100 if parameter is 1
}
);
}


[TestMethod] // Method 2
public void ConditionalMethodInputParameterWithDo()
{
var mock = new MockRepository();
var subject = mock.DynamicMock();
int result;

With.Mocks(mock).Expecting
(
delegate
{
Expect.Call(subject.Test("1")).IgnoreArguments().Do(
(Func) delegate(string s)
{
if (s == "1")
return 0;
if (s=="2")
return 2;
return 0;
}
);
}
).Verify(
delegate
{
result = subject.Test("5"); // Return 0 if parameter is not 1 or 2.
}
);
}



Comments

Popular posts from this blog

OpenCover code coverage for .Net Core

Android Programmatically apply style to your view

Using Custom DLL with IronPython / Scripts