- Spring 5.0 Microservices(Second Edition)
- Rajesh R V
- 219字
- 2021-07-02 19:45:02
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.
- LabVIEW2018中文版 虛擬儀器程序設(shè)計(jì)自學(xué)手冊(cè)
- 區(qū)塊鏈:以太坊DApp開(kāi)發(fā)實(shí)戰(zhàn)
- Mastering Ubuntu Server
- Python神經(jīng)網(wǎng)絡(luò)項(xiàng)目實(shí)戰(zhàn)
- Podman實(shí)戰(zhàn)
- 人人都懂設(shè)計(jì)模式:從生活中領(lǐng)悟設(shè)計(jì)模式(Python實(shí)現(xiàn))
- Scala程序員面試算法寶典
- C編程技巧:117個(gè)問(wèn)題解決方案示例
- 算法圖解
- Continuous Delivery and DevOps:A Quickstart Guide Second Edition
- HTML5移動(dòng)Web開(kāi)發(fā)
- PHP+MySQL Web應(yīng)用開(kāi)發(fā)教程
- ASP.NET Core and Angular 2
- 創(chuàng)新工場(chǎng)講AI課:從知識(shí)到實(shí)踐
- HTML5 Game Development by Example:Beginner's Guide(Second Edition)