Dependency需要添加Junit5:
<!-- Junit dependency --> <dependency> <groupId> org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.1.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-launcher</artifactId> <version> 1.1.0 </version> <scope>test</scope> </dependency> <!-- Junit dependency -->
在test class上加入:
@RunWith(SpringRunner.class) @SpringBootTest(classes=XXX(main class).class)
加入定义:
@Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc;
预操作:
@Before public void setUp() throws Exception{ mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();//建议使用这种 }
Test方法:
注意: 此时Test Annotation的类不要引错,正确的应该是 import org.junit.Test;
*
@DisplayName("Test Login Controller") public void test() throws Exception { //需要传入的参数 User user = new User(); user.setUserName("XXX"); user.setPassWord("XXX"); MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.post("/login") .contentType(MediaType.APPLICATION_JSON) .content(JSON.toJSONString(user))) .andReturn(); System.out.println("result ==========" + mvcResult.getResponse().getContentAsString()); }