而不用创建另一个我可以注入的类。是否可以模拟javax.mail.Transport,以便在JavaEE7上对Transport.send()方法进行一些模拟测试?
发布于 2013-07-04 08:42:41
跟随Bill Shanon的解决方案,因为Dumbster没有当前可用的Maven Central工件,所以我使用了GreenMail。
然后我使用了以下代码:
final GreenMail mailServer = new GreenMail();
mailServer.start();
final Properties mailSessionProperties = new Properties();
mailSessionProperties.put("mail.smtp.port", String.valueOf(mailServer.getSmtp().getPort()));
final javax.mail.Session mailSession = javax.mail.Session.getInstance(mailSessionProperties);
testObject.setMailSession(mailSession);这样,即使有对Transport.send(message)的静态调用,testObject也不需要更改。
发布于 2015-04-04 01:54:25
如果您想要的是在测试时调用而不是调用Transport.send,那么您可以使用以下代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest(javax.mail.Transport.class)
public class MyClassTest {
@Before
public void before() throws Exception {
suppress(method(Transport.class, "send", Message.class));
}
}另请参阅https://groups.google.com/forum/#!topic/powermock/r26PLsrcxyA
发布于 2017-10-20 11:53:32
另一种尚未讨论的方法是将对Transport.send(消息)的调用包装在委托调用的类中。这在你的代码库中有一点开销,但它允许你模拟你的委托类并创建你想要的结果。
public class TransportDelegator {
public void send(Message msg) throws MessagingException {
Transport.send(msg)
}
}然后模拟TransportDelegator,就像您在使用的任何框架中一样。
https://stackoverflow.com/questions/17457386
复制相似问题