Mocking JavaMail
On my current project we have to send email when certain things happen. After some googeling I could not find a good way to test the mail code with mocks so I spent a bit of time rooting around in the JavaMail api and various open source implementations that I could find. This is what I found.
First I created a mock transport class.
public class MockJavaMailTransport extends Transport {
public static Set messages = new HashSet();
public MockJavaMailTransport(Session arg0, URLName arg1) {
super(arg0, arg1);
}
public void sendMessage(Message arg0, Address[] arg1)
throws MessagingException {
System.err.println("Sending message '" + arg0.getSubject() + "'");
messages.add(arg0);
}
public void connect() throws MessagingException {
System.err.println("connect()");
}
public void connect(String arg0, int arg1, String arg2, String arg3)
throws MessagingException {
System.err.println("connect(String = " + arg0 + ", int = " + arg1 + ", String = " + arg2 + ", String = " + arg3 + ")");
}
public void connect(String arg0, String arg1, String arg2)
throws MessagingException {
System.err.println("connect(String = " + arg0 + ", String = " + arg1 + ", String =" + arg2 + ")");
}Then with the Service Provider type functionality built into JavaMail you tell JavaMail what implementation to use. To do that you need two file in the META-INF directory of a jar file on the classpath (JavaMail will search all jar files). The two files are javamail.providers and javamail.address.map.
The first file javamail.providers contains, protol, type, class and vendor. My file looks like this
protocol=smtp; type=transport; class=....MockJavaMailTransport; vendor=Wunder Widgtz Inc.;
The second file javamail.address.map tells JavaMail what transport to use (I don't know what rfc822 is but it works :-). The file looks like this;
I put these two files into the META-INF directory of the junit jar files and JavaMail picks them up and uses my mock transport. I use the messages Set in the mock transport to make sure the correct # of messages is sent.
Happy Mocking
Have you seen Dumbster? (http://quintanasoft.com/dumbster/) I've seen it used around for testing email functions...
Posted by Peter Daugavietis on January 06, 2005 at 05:10 PM MST #
[Trackback] From Bill Dugney's "article":http://bill.dudney.net/roller/trackback/bill/Weblog/mocking_javamail found quite an interesting tool - "Dumbster":http://quintanasoft.com/dumbster/ for testing emails. Besides "Dumbster":http://quintanasoft.com/dumb...
Posted by Mallim Ink (Beta) on January 08, 2005 at 12:12 AM MST #