C# – Using Rhino Mocks how can I set a property of a parameter for a Mocked method

cmockingrhino-mockssyntaxunit testing

Using the new Rhino Mocks 3.5 Arrange/Act/Assert (AAA) Testing style, I'm having problems writing a test.

I have a method that calls a method on a repository class. ActivateFoo, where my Foo object has an IsActive property. The result of the ActivateFoo object should change the property.

Here is sample code:

[TestMethod]
public void Should_update_foo_to_active_inside_of_repository()
{
  // arrange
  var repo = MockRepository.GenerateMock<IRepository>();
  var foo = new Foo() { ID = 1, IsActive = false };
  var target = new Presenter(repo);
  repo.Expect(x => x.ActivateFoo(foo)).Return(true);

  // act
  target.Activate(foo);

  // assert
  Assert.IsTrue(foo.IsActive);
  repo.VerifyAllExpectations();  
}

I'm guessing that the key piece of code would be inbetween "ActivateFoo(foo))." and "Return(true);".

One point to clarify how the method chaining stuff works behind the scenes, If there is code written on the line I expect, does it matter if it is after Return() or before? (unless of course the solution is using the MethodOptions overload of Expect, or something else).

Thanks in advance for any help.

Best Answer

You might want to try something out like this using the Do handler. I honestly feel ActivateFoo should be void return type. But here's the code for ActivateFoo with bool return type.

    [TestMethod]
    public void Should_update_foo_to_active_inside_of_repository()
    {
        // arrange
        var repo = MockRepository.GenerateMock<IRepository>();
        var foo = new Foo() { ID = 1, IsActive = false };
        var target = new Presenter(repo);
        repo.Expect(x => x.ActivateFoo(foo)).
            Do(new ActivateFooDelegate(ActivateFooDelegateInstance));
        // act
        target.Activate(foo);

        // assert
        Assert.IsTrue(foo.IsActive);
        repo.VerifyAllExpectations();
    }

    private delegate bool ActivateFooDelegate(Foo f);

    public bool ActivateFooDelegateInstance(Foo f)
    {
        f.IsActive = true;
        return f.IsActive;
    }
Related Topic