views:

158

answers:

2

I have a class like so:

public class ClassA
{
    public bool MethodA()
    {
      //do something complicated to test requiring a lot of setup
    }
    public bool MethodB()
    {
         if (MethodA())
             //do something
         else
             //do something else
         endif
    }
}

I have tests for MethodA and want to test MethodB, but all I want to do is to verify that if MethodA returns true that something happens and if MethodA returns false that something else happens. Can I do this with Rhino Mocks? Or do I have to set up all of the same mocks that I have already in the tests for MethodA?

+1  A: 

It's hard to say if this is doable without the context, but one solution could to extract MethodA() to its own class so that you could have MethodB() invoking MethodA() on a mock object that'll act as your unit test wish.

Another possibility is to subclass ClassA in your unit tests and to override MethodA() to return true or false depending on your unit test.

//--- pseudo-code 
public ClassAMethodAReturnTrue : public ClassA { 
  public bool MethodA() { return true; } 

  ...

Then in your tests, you instantiate ClassAMethodAReturnTrue instead of ClassA. You'll write ClassAMethodAReturnFalse likewise.

philippe
So basically you are saying that it is not possible. I don't want to move the methods to other classes or create sub classes, so I suppose that I'll have to bite the bullit and mock the calls inside methodA again.
No you can subclass ClassA *in your tests* just to redefine MethodA.
philippe
Ahh. ok I get you now, sorry. Yeah this would be another approach that would work. Thanks.
+1  A: 

You might have to extract an interface out of the class or make it abstract, I'm reasonbly sure that Rhino.Mocks can mock classes and interfaces. Which means you should be able to do something like this:

ClassA myClass = MockRepository.PartialMock(typeof(ClassA));

Expect.Call(myClass.MethodA).Return( true );

MockRepository.ReplayAll()
Assert.AreEqual( false, myClass.MethodB() )
MockRepository.VerifyAll()

The syntax might be a little off but that should allow MethodB to be tested independently of MethodA

Darren
This works, but only if the method on the class being partially mocked is virtual. Thanks, I knew it must be possible.