问题
在《Maven实战》这本书的里,有一个GreenMail
邮件测试的示例代码,完整的代码见这里,在运行mvn clean test
的时候,一直出现如下的错误。
Exception in thread "Thread-0" java.lang.RuntimeException: java.net.BindException: 地址已在使用 (Bind failed)
at com.icegreen.greenmail.smtp.SmtpServer.run(SmtpServer.java:54)
Caused by: java.net.BindException: 地址已在使用 (Bind failed)
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.<init>(ServerSocket.java:237)
at com.icegreen.greenmail.AbstractServer.openServerSocket(AbstractServer.java:51)
at com.icegreen.greenmail.smtp.SmtpServer.run(SmtpServer.java:48)
解决
修改 test 中的 Before 代码为:
@Before
public void startMailServer()
throws Exception
{
ServerSetup setup = new ServerSetup(3025,"localhost","smtp");
greenMail = new GreenMail(setup);
greenMail.start();
}
同时设置 properties
文件,电子邮件发件人端口设置为与上面相同,请注意协议/主机/端口:
email.protocol=smtp
email.host=localhost
email.port=3025
email.username=to@localhost.com
email.password=to@localhost.com
email.auth=true
email.systemEmail=from@localhost.com
然后运行 mvn clean test
测试通过。