- Create an interface that wraps the functionality of calling db, sending emails, ...
- Write an implementation of your class and load this class into a dependent class using DI
- Use the Mock framework to create a Mock object and set it to expectations in the unit test.
Here is an example of pseudo code (the Moq layout generator used here ):
interface IEmailer
{
void Send(Email email);
}
class RealEmailer : IEmailer
{
public void Send(Email email)
{
}
}
class UsesEmailer
{
private IEmailer _emailer;
public UsesEmailer(IEmailer emailer)
{
_emailer = emailer;
}
public foo(Email email)
{
_emailer.Send(email);
}
}
class MyUnitTest
{
[Test]
public Test_foo()
{
Mock<IEmailer> mock = new Mock<IEmailer>();
Email m = new Email();
mock.Expect(e => e.Send(It.Is<Email>(m)));
UsesEmailer u = new UsesEmailer(mock.Object);
u.Send(m);
mock.Verify();
}
}
UPDATE
Now, if you are testing RealEmailer, there are several ways, but basically you will have to configure the test to send you an email, and you will check. This is not quite a unit test, since you not only check your code, but also the configuration, network, exchange server ... in fact, if you make it RealEmailersmall, having a small code, you can skip the block test for it.
source
share