Skip to content

Instantly share code, notes, and snippets.

@jcsirot
Created August 3, 2012 11:15
Show Gist options
  • Save jcsirot/3246719 to your computer and use it in GitHub Desktop.
Save jcsirot/3246719 to your computer and use it in GitHub Desktop.
SMTP server mock as a JUnit TestRule
package com.chelonix.selenium;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.dumbster.smtp.SimpleSmtpServer;
import com.dumbster.smtp.SmtpMessage;
import com.google.common.collect.Lists;
import org.junit.rules.ExternalResource;
/**
* A JUnit Rule which runs a mock SMTP server
*
* @see org.junit.rules.TestRule
*/
public class MockSMTPRule extends ExternalResource
{
private int port = SimpleSmtpServer.DEFAULT_SMTP_PORT;
private SimpleSmtpServer smtp;
/**
* Creates a SMTP server listening on port 25.
*/
public MockSMTPRule()
{
}
/**
* Creates a SMTP server listening on the given port.
* @param port the SMTP port
*/
public MockSMTPRule(int port)
{
this.port = port;
}
public synchronized int getReceivedEmailSize()
{
return smtp.getReceivedEmailSize();
}
public synchronized Iterator getReceivedEmail()
{
return smtp.getReceivedEmail();
}
public List<SmtpMessage> getReceivedEmailAsList()
{
return Lists.newArrayList((Iterator<SmtpMessage>)getReceivedEmail());
}
@Override
protected void after()
{
smtp.stop();
super.after();
}
@Override
protected void before() throws Throwable
{
super.before();
smtp = SimpleSmtpServer.start(port);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment