Stub setter in Rhino Mock partial mock

1.3k views Asked by At

I'm following the accepted answer in this question but I'm getting a NullReferenceException.

What I need is having a partial mock stub a property (both getter and setter) to behave like a stub (as a simple automatic property). Currently I am able to stub the getter but not the setter.

Is this possible?

EDIT: this is a simple example, I hope it helps explaining my problem.

public class SomeClass
{
 public virtual string SomeProperty
 {
  get{ return SomeMethodDependingOnDBOrAspSession(); }
  set{ SomeMethodDependingOnDBOrAspSession(value); } // I want to avoid calling this setter implementation
 }
}

var partialMock = MockRepository.GeneratePartialMock<SomeClass>();
partialMock.Stub(p => p.SomeProperty); // I want SomeProperty to behave as an automatic property
1

There are 1 answers

2
Jeff B On BEST ANSWER

When using a PartialMock you can get auto-implemented property like behavior by using PropertyBehavior feature of Rhino Mocks. Given the class in your question, the following nunit test passes for me.

[Test]
public void TestPartialMock()
{
  var someClass = MockRepository.GeneratePartialMock<SomeClass>();
  someClass.Stub(x => x.SomeProperty).PropertyBehavior();

  string val = "yo!";
  Assert.DoesNotThrow(() => someClass.SomeProperty = val);
  Assert.AreEqual(val, someClass.SomeProperty);
}

If you don't need a PartialMock you could use a Stub which has property behavior by default. You'd simply replace the first two lines of the test with:

var someClass = MockRepository.GenerateStub<SomeClass>();