junit如何测试controller接口
时间: 2023-06-03 20:02:35 浏览: 166
可以使用MockMvc来模拟HTTP请求,测试Controller接口。例如:
```
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testGetUser() throws Exception {
String result = mockMvc.perform(MockMvcRequestBuilders.get("/user/{id}", 1))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
System.out.println("返回结果:" + result);
}
}
```
这里使用MockMvc模拟HTTP GET请求,测试UserController中的getUser()方法。