tags:

views:

702

answers:

5

Hi, Told by my boss to use Moq and that is it. I like it but it seems that unlike MSTest or mbunit etc... you cannot test internal methods

So I am forced to make public some internal implementation in my interface so that i can test it.

Am I missing something?

Can you test internal methods using Moq?

Thanks a lot

+3  A: 

If you have many code that isn't tested by the public methods, you probably have code that should be moved to another classes.

As said in another answer, you can use the InternalsVisibleTo attribute for that. But that doesn't mean you should do it.

eglasius
A: 

Your initial presumption that it is necessary to test internal method is a common beginners misconception about unit testing.

Granted, there may exist cases where private methods should be tested in isolation, but the 99% common case is that the private methods are being tested implicitly because they make the public methods pass their tests. The public methods call the private methods.

Private methods are there for a reason. If they do not result in external testable behaviour, then you don't need them.

Do any of your public tests fail if you just flat out delete them? If yes, then they are already being tested. If not, then why do you need them? Find out what you need them for and then express that in a test against the public interface.

A main benefit with TDD is that your code becomes easy to change. If you start testing internals, then the code becomes rigid and hard to change.

Tormod
A: 

There is nothing wrong with making the internals visible to other classes for testing. If you need to test the internals of a class, by all means do so. Just because the methods are not public does not mean you should ignore them and test only the public ones. A well designed application actually will have a majority of the code encapsulated within your classes in such a way that they are not public. So ignoring the non-public methods in your testing is a big mistake IMHO. One of the beauties of unit testing is that you test all the parts of your code, no matter how small and when your tests are all up and running at 100% it is a very reasonable assumption that when all these parts are put together, your application will work properly for the end user. Of course verifying that latter part is where integration level tests come in - which is a different discussion. So test away!!!

jle
A: 

InternalsVisibleTo is your friend for testing internals. Remember to sign your assemblies and you're safe.

kzu