Testing private method with Moq doesn't work
I am using Moq and I am sort of new to it. I need to test a private method.
I have 2 assemblies:
CustomerTest.dll
CustomerBusiness.dll
So CustomerTest dll has a class as follows:
[TestFixture]
public class CustomerTestFixture
{
var customerMock=new Mock<ICustomer>()
customerMock.Protected().Setup<bool>("CanTestPrivateMethod").Returns(true);
etc...
}
CustomerBusiness.dll has
public interface ICustomer { void Buy(); }
public class Customer:ICustomer
{开发者_开发问答
public void Buy()
{
etc...
}
protected virtual bool CanTestPrivateMethod()
{
return true;
}
}
I get the following error
System.ArgumentException : Member ICustomer.CannotTestMethod does not exist.
at Moq.Protected.ProtectedMock`1.ThrowIfMemberMissing(String memberName, MethodInfo method, PropertyInfo property)
at Moq.Protected.ProtectedMock`1.Setup(String methodOrPropertyName, Object[] args)
I have also added [assembly: InternalsVisibleTo("CustomerTest.CustomerTestFixture")
but with no difference!
What Am I doing wrong. I know my Interface has not such a method.That is the point as my method must be private. Can you help with an example?
When you create a mock object, it implements virtual and abstract members of the type or interface to be mocked.
By creating a Mock<ICustomer>
, it implements the one method of the customer interface. It has no knowledge of the method you added in the Customer class. If you need to mock that method, you need to create a Mock<Customer>
.
精彩评论