Spring Boot Testing with JUnit MockServerRule and TestRestTemplate
1. Test Class
@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class TestClass {
public static final int MOCK_SERVER_PORT;
static {
MOCK_SERVER_PORT = SocketUtils.findAvailableTcpPort();
System.setProperty("MOCK_SERVER_PORT", String.valueOf(MOCK_SERVER_PORT));
}
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate testRestTemplate;
@Value(value = "${app.name}")
private String appName;
@Value("${server.servlet.context-path}")
private String contextPath;
@Rule
public MockServerRule mockServer = new MockServerRule(this, false, MOCK_SERVER_PORT);
@Test
public void testCase1() throws Exception {
mockServer.getClient()
.when(request()
.withPath("/external-server")
.withMethod("POST"),
Times.once())
.respond(HttpResponse.response()
.withStatusCode(200)
.withBody("response_success"));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "text/xml");
final String body = "";
ResponseEntity<String> actual =
testRestTemplate.exchange("http://localhost:" + port + contextPath + appName + "/main",
HttpMethod.PUT, new HttpEntity<>(body, headers), String.class);
mockServer
.getClient()
.verify(
request()
.withPath("/external-server")
.withMethod("POST"),
VerificationTimes.exactly(1));
}
}
2. Test application yml
server:
servlet:
context-path: /your-context-path
app:
name: your-app-name
external-server:
url: http://localhost:${MOCK_SERVER_PORT}/external-server
3. Pom.xml
<dependency>
<groupId>org.mock-server</groupId>
<artifactId>mockserver-netty</artifactId>
<scope>test</scope>
</dependency>