views:

286

answers:

1

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?

A: 

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>.

womp
That makes sense.Do I need that InternalVisibleTo attribute in the assemblyInfo or can I delete it?Thanks
Also can you step into it.Thanks
@devnet247: removing `InternalsVisibleTo` won't affect your ability to mock stuff, but might be important for other aspects of your testing. Removing it shouldnt have effects that don't jump out at compile time.
Ruben Bartelink