简单的Controller Rest在java中的端点测试

问题描述 投票:0回答:1

我被赋予了在java Controller中创建基本端点的任务。我想出了以下内容。

@RestController
public class SimpleController{

@RequestMapping("/info")
public String displayInfo() {
    return "This is a Java Controller";
}

@RequestMapping("/")
public String home(){
    return "Welcome!";
}

}

令人讨厌的是,它是如此简单,但我想不出如何创建一个ControllerTest,我只需要测试代码。这一切都在工作和手动测试。有帮助吗?谢谢

java unit-testing spring-restcontroller
1个回答
1
投票

对于通过http的完整系统集成测试,您可以使用TestRestTemplate:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {

    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void greetingShouldReturnDefaultMessage() throws Exception {
        assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/",
                String.class)).contains("Welcome!");
    }
}

对于没有实际启动Web服务器的较轻的测试,您可以使用Spring MockMVC:https://spring.io/guides/gs/testing-web/

@RunWith(SpringRunner.class)
@WebMvcTest
public class WebLayerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnDefaultMessage() throws Exception {
        this.mockMvc.perform(get("/"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("Hello World")));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.