Testing DefaultMailManager

Before we implement DefaultMailManager, let's create the unit test, com.taskagile.domain.common.mail.DefaultMailManagerTests:

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class DefaultMailManagerTests {

@TestConfiguration
static class DefaultMessageCreatorConfiguration {
@Bean
public FreeMarkerConfigurationFactoryBean
getFreemarkerConfiguration() {
FreeMarkerConfigurationFactoryBean factoryBean = new
FreeMarkerConfigurationFactoryBean();
factoryBean.setTemplateLoaderPath("/mail-templates/");
return factoryBean;
}
}

@Autowired
private Configuration configuration;
private Mailer mailerMock;
private DefaultMailManager instance;

@Before
public void setUp() {
mailerMock = mock(Mailer.class);
instance = new DefaultMailManager("[email protected]",
mailerMock, configuration);
}
...
}

As you can see, this test class requires a DefaultMailManager instance and a mocked version of the Mailer instance, which will be used to verify the message. We also create an instance of freemarker.template.Configurationwhich is required to generate the body of the email from the template. We create an instance of FreeMarkerConfigurationFactoryBean inside the test configuration so that a Configuration instance will be auto-wired into the test.

In this test class, we have the following test methods:

  • send_nullEmailAddress_shouldFail()
  • send_emptyEmailAddress_shouldFail()
  • send_nullSubject_shouldFail()
  • send_emptySubject_shouldFail()
  • send_nullTemplateName_shouldFail()
  • send_emptyTemplateName_shouldFail()
  • send_validParameters_shouldSucceed()

The first six methods are making sure the send() method will complain about bad parameters by throwing IllegalArgumentException

The last one is to verify successful message sending. The test method looks like this:

@Test
public void send_validParameters_shouldSucceed() {
String to = "[email protected]";
String subject = "Test subject";
String templateName = "test.ftl";

instance.send(to, subject, templateName, MessageVariable.from("name", "test"));
ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class);
verify(mailerMock).send(messageArgumentCaptor.capture());

Message messageSent = messageArgumentCaptor.getValue();
assertEquals(to, messageSent.getTo());
assertEquals(subject, messageSent.getSubject());
assertEquals("[email protected]", messageSent.getFrom());
assertEquals("Hello, test ", messageSent.getBody());
}

As you can see, after invoking the send() method of DefaultMailManager, we use ArgumentCaptor to capture the message that passes to Mailer; we use the send() method, and then make assertions of its values. We won't go into the details too much here. You can check the commit record to find out the other parts that have been skipped.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.126.211