Using Moq, RhinoMocks or a similar framework, is there a way to configure a mock to implement both get and set on all properties of an object even if the interface does not?
I can certainly mock the objects manually, but would prefer to use an isolation framework like Moq or RhinoMocks to avoid creating a bunch of boilerplate classes.
Here’s some sample code:
//interface to be mocked
public interface IMyObject
{
string Property1 { set; }
}
//test method code
var mock = Moq.Mock<IMyObject>();
//...some code here to configure all properties on mock to have a get and set...
var mockObject = mock.Object;
ClassUnderTest obj = new ClassUnderTest(mockObject);
obj.MethodUnderTest();
Assert.IsTrue(!String.IsNullOrEmpty(mockObject.Property1));
Running the code as is will throw an exception on mockObject.Property1 because the IMyObject.Property1 property lacks the get accessor.
Thanks, DanO
Using Rhino Mocks, you could set an expectation for the property. This basically states that you expect the property to be set to a certain value. Using your example, an example test method body would be this:
var mock = MockRepository.GenerateMock();
mock.Expect(x => x.Property1 = “Test”);
This would check to see if
Property1had been set to “Test” at some point between the call tomock.Expectand the call tomock.MethodUnderTest(technically,Property1could be set in the constructor ofClassUnderTest).In order to test that the property was set and ignore what it was actually set to, just chain
IgnoreArgumentsto the return of theExpectcall, like so:mock.Expect(x => x.Property1 = “Test1”).IgnoreArguments();
One way to test more complex write-only properties is to use the
GetArgumentsForCallsMadeOnmethod. This allows you to retrieve a list of the arguments passed to each “call” of the property. The code to do this would be like the following:var mock = MockRepository.GenerateMock();
I am sure that Moq has similar functionality if you’d like to use that, instead.