Search code examples
c#unit-testingrhino-mocks

How to mock a property with no setter?


I am trying to Mock an Interface. The property i want to set "MockThisProperty" does not have a setter. I cannot change the Interface source. The error i get is

Previous method 'IThirdPartyInterface.get_MockThisProperty();' requires a return value or an exception to throw.

I've tried DynamicMock, Strictmock, partial mock, etc.

When I try SetupResult.For(thirdParty.MockThisProperty = mockedValue) won't compile because there is no setter.

using the latest Rhino mocks with mstest

At a loss, here is the code...

        var stuff = _Mockery.Stub<Hashtable>();
        matchItem.Add(key, "Test"); 

        var thirdParty = _Mockery.Stub<IThirdPartyInterface>();
        SetupResult.For(thirdParty.MockThisProperty).Return(stuff);

        _Mockery.BackToRecordAll();


       //more code

        _Mockery.ReplayAll();

        Assert.IsTrue(MethodToTest(thirdParty));

        _Mockery.VerifyAll();

Solution

  • This worked for me:

    var thirdParty = Rhino.Mocks.MockRepository.GenerateStub<IThirdPartyInterface>();
    thirdParty.Stub(x => x.MockThisProperty).Return("bar");
    string mockPropertyValue = thirdParty.MockThisProperty; //returns "bar"