Problem
為了要驗證程式所寄出的人或訊息是否正確,我們可以寫一些mock程式去攔截收到的內容;也可以透過java mail去接收者的信箱中把內容撈出來比對。這些方法寫起來會比較花時間,如果能透過既有的mail server,可能就會容易多了。
How to?
原先Albert有找到一套叫FakeSMTP的library,經過試驗發現它並不容易被拿進來寫UnitTest。因此直接使用它所相依的library subethamail,非常簡單就可以讓你去確認寄送者、接收者與信件內容:
private SMTPServer server; private List<String> toList = new ArrayList<>(); private String testContent; @Before public void setUp() throws Exception { try { server = new SMTPServer(new SimpleMessageListenerAdapter(new SimpleMessageListener() { @Override public void deliver(String from, String to, InputStream content) throws TooMuchDataException, IOException { logger.info("deliver {}", from); logger.info("deliver {}", to); toList.add(to); testContent = IOUtils.toString(content); } @Override public boolean accept(String from, String to) { logger.info("accept {}", from); logger.info("accept {}", to); return true; } })); server.setBindAddress(InetAddress.getByName("0.0.0.0")); server.setPort(25); server.start(); System.out.println("Start SMTP Server"); } catch (Exception e) { // Ignore } } @After public void tearDown() throws Exception { if (server !=null) server.stop(); } @Test public void test() { // do something assertEquals(2, toList.size()); assertTrue(toList.contains("test1@tonylin.org.tw")); assertTrue(toList.contains("test2@tonylin.org.tw")); assertTrue(testContent.contains("test message")); }
留言
張貼留言