GH-3062: Fix Mail Tests Hang

Resolves https://github.com/spring-projects/spring-integration/issues/3062

Reliably stop the test mail servers before the test context is destroyed.
This commit is contained in:
Gary Russell
2019-09-24 16:55:32 -04:00
parent b12657c599
commit 8ad802cdfe
2 changed files with 36 additions and 9 deletions

View File

@@ -33,13 +33,13 @@ import javax.mail.search.FlagTerm;
import javax.mail.search.FromTerm;
import javax.mail.search.SearchTerm;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.IntegrationMessageHeaderAccessor;
@@ -92,14 +92,6 @@ public class MailTests {
assertThat(n < 100).isTrue();
}
@AfterClass
public static void tearDown() {
smtpServer.stop();
pop3Server.stop();
imapServer.stop();
imapIdleServer.stop();
}
@Autowired
private MessageChannel sendMailChannel;
@@ -189,6 +181,35 @@ public class MailTests {
@EnableIntegration
public static class ContextConfiguration {
@Bean
public SmartLifecycle serverStopper() {
return new SmartLifecycle() {
@Override
public int getPhase() {
return Integer.MAX_VALUE;
}
@Override
public void stop() {
smtpServer.stop();
pop3Server.stop();
imapServer.stop();
imapIdleServer.stop();
}
@Override
public void start() {
}
@Override
public boolean isRunning() {
return true;
}
};
}
@Bean
public IntegrationFlow sendMailFlow() {
return IntegrationFlows.from("sendMailChannel")

View File

@@ -412,6 +412,8 @@ public final class TestMailServer {
protected final List<String> messages = new ArrayList<>(); // NOSONAR protected
private final List<Socket> clientSockets = new ArrayList<>();
private volatile boolean listening;
MailServer(int port) throws IOException {
@@ -445,6 +447,7 @@ public final class TestMailServer {
try {
while (!serverSocket.isClosed()) {
Socket socket = this.serverSocket.accept();
this.clientSockets.add(socket);
exec.execute(mailHandler(socket));
}
}
@@ -457,6 +460,9 @@ public final class TestMailServer {
public void stop() {
try {
for (Socket socket : this.clientSockets) {
socket.close();
}
this.serverSocket.close();
}
catch (IOException e) {