Alex
Alex

Reputation: 93

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();

Upvotes: 4

Views: 3544

Answers (2)

Stefan
Stefan

Reputation: 31

I stumbled over this post when trying to mock a property defined in an interface with no setter.

As I don't yet use Rhino and don't want another dependency than Moq, i found

mockedWithMoq.SetupGet(x => x.PropertyWithGetterOnly).Returns("foo")

will also do the work.

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160882

This worked for me:

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

Upvotes: 7

Related Questions