views:

81

answers:

1

I have a situation I've run into several times but have never found a good answer for. Suppose I have a class like the following, where one method calls another in the same class:

public class Foo
{
    public int Bar()
    {
        if (Baz())
        {
            return 1;
        }
        else
        {
            return 2;
        }
    }

    public virtual bool Baz()
    {
        // behavior to be mocked
    }
}

I want to unit test the behavior of the method Bar() depending on return values of Baz(). If Baz() were in a different class, I would call PartialMock to set up mocking behavior on that class, but it doesn't seem to work when PartialMock is used on the test class itself. Is there an easy way to do this? What am I missing?

I'm using Rhino Mocks 3.5 and .NET 2.0.

+3  A: 

You can use stubs to mock the Baz method. If you were using .NET 3.5 you'd be using lambdas but with .NET 2.0 you'd be using anonymous delegates as in the following example:

Foo f = MockRepository.GenerateStub<Foo>();
// lambda:
// f.Stub(x => x.Baz()).Return(true);
// anonymous delegate:
f.Stub(delegate(Foo x) { return x.Baz(); }).Return(true);
Console.WriteLine(f.Bar());
Jakob Christensen
I tried it and it works exactly as advertised. Thanks!
glaxaco