Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I assert /verify a Moq Protected Method?

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.

like image 381
user9969 Avatar asked Feb 01 '10 18:02

user9969


1 Answers

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.

like image 51
tvanfosson Avatar answered Oct 20 '22 00:10

tvanfosson