Introducing dependent packages:
<dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>2.23.4</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito2</artifactId> <version>2.0.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-core</artifactId> <version>2.0.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>2.0.2</version> <scope>test</scope> </dependency>
MockMvc + PowerMock + Mockito to simulate post get request, and the presence of mock doGet doPost off outside the system in the restful service request
@RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(SpringRunner.class) @prepareForTest({ HttpUtil.class // doGet doPost 使用util类,这里需要告诉UT }) @PowerMockIgnore("javax.crypto.*") @AutoConfigureMockMvc @SpringBootTest public class DemoSzlTest { @Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc; @Before public void setUp() throws Exceptioin { MockitoAnnotations.initMocks(this); // 初始化装载powerMockito mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test @DirtiesContext public void testPostDemo() throws Exception { // mock HttpResponse 对象返回 StringEntity se = new StringEntity("xxx", "xxx"); HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.Http_1_1, HttpServletResponse.SC_OK, "")); resp.setEntity(se); PowerMockito.mockStatic(HttpUtil.class);
// here Mockito.anyString () method and the actual parameters to be consistent
. PowerMockite.when (HttpUtil.doGet (Mockito.anyString () , Mockito.anyMap (), Mockito.any ())) thenReturn (resp) ; // body Contents String jsonBody = "{\" AAAA \ ": \" 1111 \ "}" ; String token = "XXXXX" ; MvcResult resultMsg = mockMvc.perform ( POST ( "/ XXX" ) .contentType (the MediaType. APPLICATION_JSON_VALUE) .accept (MediaType.APPLICATION_JSON_UTF8_VALUE) .header ( "XXXXX" , token) . content(jsonBody) // request body ).andExpect(status().isCeated()) .andReturn(); } }
HttpUtil.java categories:
public class HttpUtil { public static HttpResponse doGet(String url, Map<String, String> params, Header[] headers) { ..... 这里省略 } }
Well, subsequent content gradually added.