在springboot中我们写测试类测试service时比较容易,但当我们测试controller时一般用的是postman,本文我将介绍如何使用测试类测试controller
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
测试service类
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTests {
@Autowired
private UserService userService;
@Test
public void testAddUser() {
User user = new User();
user.setName("john");
user.setAddress("earth");
userService.add(user);
}
}
SpringBoot测试controller类
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@Slf4j
public class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void helloTest() {
MvcResult mvcResult = null;
try {
mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/url")
.accept(MediaType.APPLICATION_JSON)
.param("name", "hello"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
log.info(mvcResult.getResponse().getContentAsString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
至此,springboot测试service类和测试controller类都完成了。如果你觉得本文对你有帮助,欢迎评论、点赞、双击666 o( ̄▽ ̄)d