官术网_书友最值得收藏!

Testing Spring Boot microservice

There are multiple ways to test REST/JSON Spring Boot microservices. The easiest way is to use a web browser or a curl command pointing to the URL, like this:

curl localhost:8080

There are number of tools available for testing RESTful services such as Postman, Advanced Rest Client, SOAP UI, Paw, and more.

In this example, for testing the service, the default test class generated by Spring Boot will be used. Adding a new test case to ApplicatonTests.java results in this:

    @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationTests {
@Autowired
private TestRestTemplate restTemplate;

@Test
public void testSpringBootApp() throws JsonProcessingException,
IOException {
String body = restTemplate.getForObject("/", String.class);
assertThat(new ObjectMapper().readTree(body)
.get("message")
.textValue())
.isEqualTo("Hello World!");
}
}

Note that @SpringBootTest is a simple annotation for testing Spring Boot applications, which enables Spring Boot features during test execution. webEnvironment=WebEnvironment.RANDOM_PORT property directs the Spring Boot application to bind to a random port. This will be handy when running many Spring Boot services as part of a regression test. Also note that TestRestTemplate is being used for calling the RESTful service. TestRestTemplate is a utility class, which abstracts the lower-level details of the HTTP client, and also automatically discovers the actual port used by Spring Boot.

To test this, open a terminal window, go to the project folder, and run mvn install.

主站蜘蛛池模板: 寿光市| 临沂市| 温州市| 古丈县| 兴国县| 若羌县| 鹤岗市| 惠州市| 泉州市| 沾益县| 康平县| 宁津县| 梁河县| 峨山| 苏尼特右旗| 曲麻莱县| 鄂伦春自治旗| 鸡泽县| 天柱县| 永定县| 闽侯县| 绥中县| 永年县| 淳安县| 达尔| 喀什市| 尼木县| 黄冈市| 衡阳县| 海安县| 武安市| 八宿县| 马山县| 监利县| 辛集市| 玉门市| 宁乡县| 肇州县| 岐山县| 肃南| 惠东县|