添加 maven 支持
<!-- test --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>2.0.9</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito2</artifactId> <version>2.0.9</version> <scope>test</scope> </dependency>
创建测试类
package test; import com.alibaba.fastjson.JSONObject;import com.MyApplication;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.mock.web.MockHttpServletResponse; 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.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; @RunWith(SpringRunner.class) @SpringBootTest(classes = MyApplication.class) @AutoConfigureMockMvc public class TestEnduserApi { @Autowired MockMvc mockMvc;
@Test public void emailLogin() throws Exception { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post("/api/emailPwdLogin"); builder.param("email", "x"); builder.param("pwd","x"); builder.param("random","x"); MvcResult result = mockMvc.perform(builder).andReturn(); MockHttpServletResponse response = result.getResponse(); response.setContentType("application/json; charset=utf-8"); String content = response.getContentAsString(); System.out.println("--------- emailLogin response -----------"); System.out.println(content); } }