views:

291

answers:

6

I have a property in an interface that I have mocked using Rhino Mocks. I want to know if it was accessed in my unit test.

Is there a way to see if the property was accessed via Rhino Mocks?

I found this code here but it does not seem to work:

string name = customerMock.Name;
customerMock.AssertWasCalled(x => {var ignored = x.Name;});

I reproduced this code and I get the following:

Rhino.Mocks.Exceptions.ExpectationViolationException: IAddAddressForm.get_FirstName(); Expected #1, Actual #0..

I would like to use this syntax, but I must be missing something. I am calling it with a stub (not a mock) does that make a difference?

A: 

I believe StrictMock is what your are looking for. There is some information about it here. It's use is said to be discouraged because it can make tests too brittle, however it should help you achieve what you're trying to do.

jamesaharvey
A: 

You can check the call stack using the StackFrame class. Not very clean, but it should give the desired result...

Thomas Levesque
A: 

I usually use Moq which uses Castle so you might consider it instead/together with of Rhino Mocks. This is how you can do it there:

// expects an invocation to set the value to "foo"
mock.SetupSet(foo => foo.Name = "foo");

// or verify the setter directly
mock.VerifySet(foo => foo.Name = "foo");
Dmytrii Nagirniak
+3  A: 

Is there a way to see if the property was accessed via Rhino Mocks?

Yes. You can set up an expectation for the property. If the verification doesn't throw, then you know the property was accessed:

var mocks = new MockRepository();
IFoo foo = mocks.DynamicMock<IFoo>;
// this sets up an expectation that Name is accessed, and what it should return
Expect.Call(foo.Name).Return("John Doe"); 
mocks.ReplayAll()

// test something that uses IFoo here ...

mocks.VerifyAll();  // Throws if foo.Name was not accessed after ReplayAll()

This is all assuming that you want foo.Name to be accessed. If your goal is to verify that it is not accessed, then you should just use StrictMock instead of DynamicMock. A strict mock will throw for any unexpected calls.

Wim Coenen
+1  A: 

Turns out the syntax I was using does work. But it only works if the property is not in PropertyBehavior mode. (Which is the default for stubs and can be turned on for mocks).

Once PropertyBehavior mode is turned on, then that syntax does not work. According to Ayende you have to check the value at that point.

Vaccano
+1  A: 

If you want to assert that a method was called or a property accessed on a faked object, you should always use a mock. Stubs are for those situations where you don't want to test the interaction, but just want to make sure that a call to some object returns a certain value to make the logic flow.

martinnjensen