- 1. 使用Mock需要Mock所有涉及到得行为,这其实代表了我们是在测试实现,而不是测试执行过程。这样会导致重构的时候经常需要修改很多测试代码。测试应该只关注输入输出,只要输入输出没变,就不应该影响测试。
- 2. 增加代码复杂度。
- 3. Mock的时候会不小心屏蔽掉一些实现,增加风险
但是在实际的开发工作中,总是免不了存在外部依赖,比方说依赖某个WebService,或者某个MQ服务,再或者某个Email服务器等等,对于这些外部服务,我更趋向于Stub服务,而不是Mock服务。Stub服务是程序真的和外部的一个服务进行了交互,更符合真实情况。Stub Web Service我会使用DreamHead的Moco框架;MQ服务我会使用ActiveMQ构造一个临时的MQ服务器;而Email呢,我会使用GreeMail构建一个临时的Mail服务器。
Junit和GreenMail
假设我要测试自己的一个MailSender,我会首先把green Mail添加到测试依赖中,然后在Junit测试的setup和teardown中分别启动和关闭Mail Server即可, 代码如下:
public class MyMailSenderTest { private MyMailSender mailSender; private GreenMail mailServer; @Before public void setUp() throws Exception { mailServer = new GreenMail(new ServerSetup(12000, null, "smtp")); mailServer.start(); mailSender = new MyMailSender("localhost", 12000); } @After public void tearDown() throws Exception { mailServer.stop(); } @Test public void shouldSendEmailToServer() throws Exception { mailSender.sendEmail("Unit Test for java mail Demo"); String receivedMessage = (String) mailServer.getReceivedMessages()[0].getContent(); assertThat(receivedMessage.trim(), equalTo("Unit Test for java mail Demo")); } }
实现代码如下:
public class MyMailSender { private JavaMailSender mailSender; public boolean sendEmail() { try { MimeMessage mimeMessage = mailSender.createMimeMessage(); MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage); mimeMessageHelper.setFrom("[email protected]"); mimeMessageHelper.setTo("[email protected]"); mimeMessageHelper.setText("Unit Test for java mail Demo"); mailSender.send(mimeMessageHelper.getMimeMessage()); return true; } catch (MessagingException e) { return false; } } }
GreenMail还支持验证该消息的确是发送给了某个用户,在上面的实现中,我们要求发送给用户[email protected], 可以通过如下的代码验证如下:
@Test public void shouldSendToSpecifiedUser() throws Exception { mailSender.sendEmail("Unit Test for java mail Demo"); GreenMailUser greenMailUser = mailServer.setUser("[email protected]", null); MailFolder inbox = mailServer.getManagers().getImapHostManager().getInbox(greenMailUser); Listmessages = inbox.getMessages(); assertThat(messages.size(),equalTo(1)); String content = (String) messages.get(0).getMimeMessage().getContent(); assertThat(content.trim(), equalTo("Unit Test for java mail Demo")); }
更多用法,参加官网: http://www.icegreen.com/greenmail/