tags:

views:

42

answers:

2

I have been trying to figure this one out, how do i test that a private method is called with rhino mocks with in the class that I am testing. So my class would be something like this.

Public class Foo
{
    public bool DoSomething()
    {
       if(somevalue)
       {
          //DoSomething;
       }
       else
       {
          ReportFailure("Failure");
       }
    }

    private void ReportFailure(string message)
    {
        //DoSomeStuff;
    }
}

So my unit test is on class Foo and method DoSomething() I want to check and make sure that a certain message is passed to ReportFailure if somevalue is false, using rhino mocks.

+1  A: 

There probably is a way to do this, but in most circumstances you don't want to do this. Your unit tests shouldn't depend on hidden implementations or code. Treat your classes as black boxes when you test them, where you only have access to changing the input and testing the output.

If you are testing private method execution, you are very likely diving too far into the implementation of a given class, and you're making it difficult to change your implementation down the road without breaking tests.

mjd79
Agreed, you should design your classes for testability via the public interface. If you can't access some internal state that needs to be verified, you need a more robust public interface.
darthtrevino
I totally agree with the black-box principle, but I know some of my tests confirm that the classes I'm testing have been correctly updated internally following a method call.
Flynn1179
A: 

I agree with mjd79's answer, however if you're married to the idea of verifying that ReportFailure was called then you could change the protection level of the method to Internal, and set the InternalsVisibleTo attribute on your assembly so that it allows your unit tests to access it.

A better approach might be to mock whatever resource ReportFailure accesses, and verify that some public method on that mock is invoked.

Andrew Anderson