tags:

views:

223

answers:

1

Hi, I have a private method that should return true.I m using Nunit and MOQ So i have as follows:

   [TestFixture] 
   public class CustomerTestFixture 
   { 
       var customerMock=new Mock<ICustomer>() 
       customerMock.Protected().Setup<bool>("CanTestPrivateMethod").Returns(true); 

       // How do I assert it now since I cannot do 
        customerMock.Verify //Verify does not exists.

   } 

Could not find anything on google that tells you how to test it. as you can see I can do a set up for it but cannot assert.

Am I missing the obvious?

Thanks a lot

+1  A: 

You don't want to test a method on a mock. You want to test the method on a instance of the actual class. The way to test a private method on a class is to use an accessor. Note that VS will provide these for you automatically, or you can "roll your own" using reflection. For an internal method, you can also set InternalsVisibleTo to your test project in the AssemblyInfo.cs file.

[TextFixture]
public class CustomerTestFixture
{
   var customer = new Customer();
   var accessor = new Customer_Accessor( new PrivateObject( customer ) );

   Assert.IsTrue( accessor.CanTestPrivateMethod() );

}

When you mock an object, the intent is that that object is being used as a dependency for the actual class under test. Therefore, it's enough to be able to set up the mock object to return specific values. You're doing your assertions on the class that uses the dependency, not on the mock class. The verification step ensures that your class under test called the methods on the mock objects according to the expectations you've established.

tvanfosson
Thanks for your reply.I want my mock up object.CanTestPrivateMethod to return specific values.So if I hardcode "return true" in my private method.Can I still assert that?In my view I should not be testing a private method at all,but my collegue insists on this one.So I am just trying to figure it out how to do it using MOQ.
You're missing my point. Don't mock the object under test. Only mock it's dependencies. Create an actual instance, set up the conditions so the private method should return a specific value, then use the accessor to check that the method does, in fact, return that value. The only need for mocks would be if the instance had some dependencies that you would use inside your private method.
tvanfosson
Thanks for your time and reply.I got the point now.