3

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
Community
  • 1
  • 1
jorgehmv
  • 3,633
  • 3
  • 25
  • 39

1 Answers1

2

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>();
Jeff B
  • 8,572
  • 17
  • 61
  • 140
  • Yes, I forgot about adding virtual in the example but I'm already using this keyword in my code. The difference with your answer is that I need to use a Partial Mock, not a Stub. I updated my example – jorgehmv May 31 '13 at 14:18
  • Updated the question to use a `PartialMock` instead. – Jeff B May 31 '13 at 14:55