views:

136

answers:

2

Hi, I have seen many posts and questions about "Mocking a private method" but still cannot make it work and not found a real answer. Lets forget the code smell and you should not do it etc....

From what I understand I have done the following:

1) Created a class Library "MyMoqSamples"

2) Added a ref to Moq and NUnit

3) Edited the AssemblyInfo file and added [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] [assembly: InternalsVisibleTo("MyMoqSamples")]

4) Now need to test a private method.Since it's a private method it's not part of an interface.

5) added the following code

        [TestFixture]
            public class Can_test_my_private_method
            {
                [Test]
                public void Should_be_able_to_test_my_private_method()
                {
                    //TODO how do I test my DoSomthing method
                }
            }

            public class CustomerInfo
            {
                public string Name { get; set; }
                public string Surname { get; set; }
            }

            public interface ICustomerService
            {
                List<CustomerInfo> GetCustomers();
            }

            public class CustomerService: ICustomerService
            {
                public List<CustomerInfo> GetCustomers()
                {
                    return new List<CustomerInfo> {new CustomerInfo {Surname = "Bloggs", Name = "Jo"}};
                }

                protected virtual void DoSomething()
                {

                }
            }

Could you provide me an example on how you would test my private method? Thanks a lot

+3  A: 

The steps you're describing set Moq up to test internal classes and members so have nothing really to do with testing a protected or private method

Testing private methods is a bit of a smell, you should really test just the public API. If you feel that the method is really important and needs to be tested in isolation perhaps it deserves to be in its own class where it can then be tested on its own?

If your heart is set on testing the protected method above you can roll your own Mock in your test assembly:

public class CustomerServiceMock : CustomerService {
    public void DoSomethingTester() {
         // Set up state or whatever you need
         DoSomething();
    }

}

[TestMethod]
public void DoSomething_WhenCalled_DoesSomething() {
    CustomerServiceMock serviceMock = new CustomerServiceMock(...);
    serviceMock.DoSomethingTester();
 }

If it was private you could probably do something dodgy with reflection but going that route is the way to testing hell.


Update

While you've given sample code in your question I don't really see how you want to "test" the protected method so I'll come up with something contrived...

Lets say your customer service looks like this:-

 public CustomerService : ICustomerService {

      private readonly ICustomerRepository _repository;

      public CustomerService(ICustomerRepository repository) {
           _repository = repository;
      } 

      public void MakeCustomerPreferred(Customer preferred) {
           MakePreferred(customer);
           _repository.Save(customer);
      }

      protected virtual void MakePreferred(Customer customer) {
          // Or more than likely some grungy logic
          customer.IsPreferred = true;
      }
 }

If you wanted to test the protected method you can just do something like:-

[TestClass]
public class CustomerServiceTests {

     CustomerServiceTester customerService;
     Mock<ICustomerRepository> customerRepositoryMock;

     [TestInitialize]
     public void Setup() {
          customerRepoMock = new Mock<ICustomerRepository>();
          customerService = new CustomerServiceTester(customerRepoMock.Object);
     }


     public class CustomerServiceTester : CustomerService {    
          public void MakePreferredTest(Customer customer) {
              MakePreferred(customer);
          }

          // You could also add in test specific instrumentation
          // by overriding MakePreferred here like so...

          protected override void MakePreferred(Customer customer) {
              CustomerArgument = customer;
              WasCalled = true;
              base.MakePreferred(customer);
          }

          public Customer CustomerArgument { get; set; }
          public bool WasCalled { get; set; }
     }

     [TestMethod]
     public void MakePreferred_WithValidCustomer_MakesCustomerPreferred() {
         Customer customer = new Customer();
         customerService.MakePreferredTest(customer);
         Assert.AreEqual(true, customer.IsPreferred);
     }

     // Rest of your tests
}

The name of this "pattern" is Test specific subclass (based on xUnit test patterns terminology) for more info you might want to see here:-

http://xunitpatterns.com/Test-Specific%20Subclass.html

Based on your comments and previous question it seems like you've been tasked with implementing unit tests on some legacy code (or made the decision yourself). In which case the bible of all things legacy code is the book by Michael Feathers. It covers techniques like this as well as refactorings and techniques to deal with breaking down "untestable" classes and methods into something more manageable and I highly recommend it.

sighohwell
I see where you going and makes sense.Just started working on a new projects and tons of code and not unit tests.Is it a good work around to refactor all these private method into an internal class and make them public?Is it possible to test an internal class?
It's possible to test an internal class by using the InternalsVisibleTo attribute, like you described at the beginning of your question.
sighohwell
Picking up on the rest of the question. The deeper question is why do you want to test a private member in the first place, and why do you want Moq to do it?
sighohwell
Personally I find Moq useful for isolating dependencies when testing a class that depends on ICustomerService. What you seem to be asking is how to test the implementation of ICustomerService and beyond injecting dependencies that the service might depends upon I'm not really sure how Moq can help you do this.
sighohwell
Instead try and test the public API, if you want to test if the protected method gets called during the API call that's easy enough to do by subclassing CustomerService in your test code.
sighohwell
Ultimately libraries like Moq are just tools meant for a particular purpose (i.e. mocking and isolating external dependencies). There are plenty of other testing patterns when it comes to interacting with protected members which will offer you far more type safety than using Moq.
sighohwell
It's wrong to test a private method and I agree.However I am dealing with loads of legacy code and they have now decided to add some tests around it.How would you approach it?I tried to say that you dont test private methods but it's fallen on deaf hears.So either we leave things as there are or we need to refactor the lot."Testing by subclassing CustomerService in your test code."Quick Example?"Testing patterns interacting with protected methods" can you provide a link I would like to learn about it.Thanks for your time
The canonical source for testing legacy code is "Working Effectively With Legacy Code" by Michael Feathers. It's packed full of tips that let you break untested classes into some thing more manageable."The Art of Unit Testing" by Roy Osherove is a good source as well and "xUnit Test patterns" by George Meszaros is more than likely to have something in it too.
sighohwell
thank a lot for your time and effort.It's been a great great help.
+1  A: 

There are appear to be two parts to your question.

  1. How do I mock a protected method:

    http://www.clariusconsulting.net/blogs/kzu/archive/2008/07/05/MockingprotectedmemberswithMoq.aspx

  2. how do I trigger the invocation of this protected/private behavior in my test

    The answer here is that you trigger it via something public. If you want to force it to happen directly (i.e., actually invoke something protected directly without an intermediate helper, you'll need to use reflection. This is by design - the languages are providing the protection mechanisms as a way of enforcing encapsulation.

I suggest you think about what you're trying to demonstrate/prove in your test though. If you find yourself writing a test that's complicated, you're Doing It Wrong. Perhaps what you want to do can be broken down into independent tests? Perhaps you are writing an integration test, not a unit test? But there are lots of articles out there on bad tests, and more an more will make sense to you as you learn to write good tests. Two of my favourites are http://www.codethinked.com/post/2009/06/30/What-is-Unit-Testing.aspx and http://www.codethinked.com/post/2009/11/05/Ite28099s-Okay-To-Write-Unit-Tests.aspx

Ruben Bartelink
thanks for your reply.I have just joined a company and they have developed tons and tons of code without a single unit test.They have never done TDD and such.And find difficult to explain the concept of "you should not test a private method" etc.. you test the behavior not the implementation etc....Now lets forget for a second what we should and should not do.Is it possible to test directly a private method using Moq?I seems to have taken all the necessary step but I keep getting answers of what I should and not should do(which I am grateful) but not practical examples.Thanks!
those links are very very good!I like them I might forward them.(To help my case)
Ruben,as said if refactor these internal methods and make them public into and internal class will I be in the same position? Just trying to think of workarounds that are no "hacks"
Based on your conversation with @sighohwell... You obv want to put Working Effectively With Legacy Code on your reading list too. But my bet is that you'll find xUnit Test Patterns most useful of all - you have the basic mechanical understanding but just need to tie it all together
Ruben Bartelink
BTW I just +1d @sighohwell's answer. Your way of feeding back to people that you consider them to be helping is by +1ing. Look at the amount of effort s/he's put in trying to get points across.
Ruben Bartelink
Ruben Bartelink
Really looking forward to getting the opportunity to answer another question like this and then get to guess whether my time was a complete waste or not :P i.e., we still dont know whether you wanted to test privates or something that triggers a protected. And we dont know whether you chose to hand-write mocks and/or whether you understood the points
Ruben Bartelink