I have a method like
public abstract class Base
{
public void MethodUnderTest();
}
public class ClassUnderTest : Base
{
public override MethodUnderTest()
{
if(condition)
{
IMail mail = new Mail() { /* ... */ };
IMailer mailer = new Mailer() { /* ... */ }
mailer.Send(mail);
}
else
{
/* ... */
}
}
}
I have unit tests for this method, and the mail gets sent to myself, so it’s not terrible (better than no test) but I’d prefer not to send the mail.
- The problem I have is that I don’t want test specific code in the class (ie. if (testMode) return; instead of sending the mail)
- I don’t know lots about DI, but I considered passing a mock IMailer into MethodUnderTest except that it overrides the base class, and no other class that derives from Base needs an IMailer object (I don’t want to force implementers of Base to take an unnecessary IMailer in MethodUnderTest)
What else can I do?
(note: IMail and IMailer are part of an external library for sending e-mail. It’s written in house, so I can modify it all I like if necessary, though I can’t see a need to in this situation)
A standard approach using dependency injection would be to require an
IMailerinClassUnderTests‘s constructor. If you do that, you pass a mock mailer into your tests, and the base class doesn’t need to know anything about mailing or mailers.If that’s undesirable for some reason (this is pretty rare, it’s usually only relevant when you don’t control the underlying classes), you can use setter injection (“property injection”).