Often times, a class would not have a direct output; it manipulates its dependencies, making them do things.
For example:
internal interface IEmailer
{
void SendEmail();
}
class ReportSender
{
public IEmailer Emailer { get; set; }
public ReportSender(IEmailer emailerToUse)
{
Emailer = emailerToUse;
}
public void SendReport()
{
// Do whatever is needed to create the report
Emailer.SendEmail();
}
}
Creating a mock of IEmailer and make it expect IEmailer.SendEmail() seem to be exposing too much of the innards of the class and making the test fragile.
But I can’t think of any other way to test this class.
How should we write unit tests for such a class?
Making a mock of IEmailer doesn’t by itself expose too much of the class. Rather, it makes it open for extensibilty.
There’s a certain tendendency that heavily relying on interaction-based testing (i.e. mocks) makes tests more fragile, but this is more of a design issue than an issue with mocks.
The Hollywood Principle can be really helpful here, because if your dependencies are mostly designed around
voidmethods, dynamic mocks like Moq or Rhino Mocks will generally just ignore the method calls unless you specifically tell them to care about a particular one.