Testing email contact form with JWebUnit without sending the email

199 Views Asked by At

I have a Java web application built using servlet and JSP pages. I have written some integration tests using JWebUnit (http://jwebunit.sourceforge.net).

I have a test method like this:

@Test
public void testContact() {
beginAt("contact");
assertResponseCode(200);

assertFormPresent("form_contact");
assertElementPresent("page_contact_form_uitleg");
assertTextInElement("page_contact_form_uitleg", getMessage("pagina.contact.uitleg"));

assertFormElementPresent("form_naam");
assertFormElementPresent("form_email");
assertFormElementPresent("form_boodschap");

setTextField("form_email", "[email protected]");
setTextField("form_wachtwoord", "Joel1234!");
}

However when I submit the form in the test method the email is sent out. Is there a way I can test this email functionality like there is in Rails? In Rails when you are in the test environment, the app is not sending out real emails. Instead it is adding those emails to some sort of test queue where you can check if the email would have been sent.

Can I use something like that in a Java web app?

2

There are 2 best solutions below

0
On

There is nothing built into JSP/Servlets that will let this happen automatically; Rails is a framework, while JSP/Servlets is lower-level. But your app presumably has a few environment-specific properties stored in a text file or database; if you create a boolean one like suppressMailSend and then use this boolean to control whether your mail-sending code actually sends the mail (and perhaps logs the message to your app logs if not), that'd do it. (A helpful thing can also be to conditionally send these mails not to their intended recipient but to yourself -- with the "real" recipient addr appended to the subject line so you know to whom the mail would be sent to in production -- helpful if you want to see what the sent mails look like.)

0
On

Post Hoc is a Java/JSP application that acts like an SMTP server, and will receive the emails from your application, and store them in a list with a user interface that allows you to inspect the emails. It is easy to install and very low overhead. Freely available, open source.

Git hub: Git Hub Site

Also, see blog post: PostHoc: Testing Apps that Send Email