java中的简单控制器Rest端点测试
我被指派在java控制器中创建一个基本端点的任务。我想出了下面的答案java中的简单控制器Rest端点测试,java,unit-testing,spring-restcontroller,Java,Unit Testing,Spring Restcontroller,我被指派在java控制器中创建一个基本端点的任务。我想出了下面的答案 @RestController public class SimpleController{ @RequestMapping("/info") public String displayInfo() { return "This is a Java Controller"; } @RequestMapping("/") public String home(){ return "Welcome!"; }
@RestController
public class SimpleController{
@RequestMapping("/info")
public String displayInfo() {
return "This is a Java Controller";
}
@RequestMapping("/")
public String home(){
return "Welcome!";
}
}
令人恼火的是,它非常简单,但我想不出如何创建ControllerTest,我所需要的只是测试代码。这是所有工作和手动测试。有什么帮助吗?感谢通过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:
在JUnit5中包含这一点可能很有用,您可以使用
@ExtendWith(SpringExtension.class)
谢谢大家的帮助!
@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")));
}
}