Example:
public interface IFoo
{
bool DoSomething();
}
public class Foo:IFoo
{
public bool DoSomething()
{
var result = DoOtherThing();
...
return result;
}
public bool DoOtherThing()
{
...
}
}
My normal TDD approach would be to write unit tests on both the DoSomething() and DoOtherThing() methods. But this would be very hard to do if DoOtherThing was a private method. I have also read that testing private methods is a no-no.
Is it considered acceptable to have public methods on a class in order to facilitate code coverage and testing, even if the purpose of the class is only to be accessed through its (IFoo) interface? Normally I would put methods that are outside of the scope of the interface as private methods, but this does not allow you to efficiently test all of your code. Making the method public allows you to right tests on the Foo class, but it doesn’t seem correct, at least to me, to have public methods that aren’t called from outside the class. Is this way considered best for TDD or is there a better way?
Public methods are public because they should be accessible. Make it private if it’s not intended to be invoked from the outside.
If you fail to get code coverage you might want to break up your class into multiple classes and use composition instead.
Things that are hard to test usually indicates a design flaw.
Update
Thats two responsibilites (SRP). Composing an email and actually send it. I would not do that in the same class. It will also be code duplication if all your email classes compose their messages and then send them. How do you handle network failure? Do you duplicate those checks too?
Do something like:
Update 2
The reason to why you should not test private methods is as far as I concern a quality measure. It’s likely that you are breaking some fundamental principles (SOLID) if you get low test coverage.
So it’s better to take time and reflect over the class design instead of trying to test private methods.