Why can't I change the return value in a Rhino Mocks stub object?

限于喜欢 提交于 2020-01-14 10:44:12

问题


Forgive me if this is a stupid question, but I'm fairly new at mocking, and am trying to get my head around it.

I have some unit tests (using the built-in Visual Studio 2010 Professional testing features), which use a stub that is needed by a method. I created a stub, and set the default return values for a couple of properties and a method, and all works well. I have a static class that sets up the stub, and this is used in the TestInitialize method to set up the stub...

public static AppointmentReminderProviderInterface GetMockProvider() {
  AppointmentReminderProviderInterface provider = MockRepository.GenerateStub<AppointmentReminderProviderInterface>();
  provider.Stub(p => p.ContactName).Return(MockProviderContactName);
  provider.Stub(p => p.ContactEmail).Return(MockProviderContactEmail);
  return provider;
}

Note that MockProviderContactName and MockProviderContactEmail are local string properties that contain default data for the provider. The unit tsts that check to see if things work as expeced with the default data all pass fine.

However, I now want to test what happens when one of these properties contains duff data. I thought I could just set this on the stub, but it isn't working. The test method contains the following lines...

_provider.Stub(p => p.ContactEmail).Return("invalid");
Debug.WriteLine("Provider email: <" + _provider.ContactEmail + ">");

The Debug.WriteLine() shows me that, despite the fact that I have set the ContactEmail property to return "invalid" it still returns the default email address. This causes my test to fail, as I'm expecting it to throw an exception, and it doesn't.

Anyone any idea why I can't change the return value of this property?

Thanks for any help.


回答1:


As a tricky but working solution I'd suggest to use Do handler here. It allows to implement some logic for stubbed method/property.

See example:

var providerContactEmail = "Email1";

provider
    .Stub(p => p.ContactEmail)
    .Do((Func<string>)(() => providerContactEmail));
// here provider.ContactEmail returns "Email1"

providerContactEmail = "Email2";
// now provider.ContactEmail returns "Email2"

But in my opinion it is much better if the solution can be found which allows to don't change return value in the middle of test. :)




回答2:


Try changing

_provider.Stub(p => p.ContactEmail).Return("invalid");

To

_provider.ContactEmail = "invalid";

Assuming ContactEmail has a setter, this should work. If this doesn't resolve your issue, I'd follow Alexander Stepaniuk's advice and refactor your test so that you're not adding multiple behaviors for the same stub; I think that has something to do with your issue.



来源:https://stackoverflow.com/questions/13918281/why-cant-i-change-the-return-value-in-a-rhino-mocks-stub-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!