引入依赖的包:
<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 来模拟post get请求,并mock掉service中存在doGet doPost外部系统的restful请求
@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);
// 这里的 Mockito.anyString() 要和 实际方法参数保持一致
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(MediaType.APPLICATION_JSON_VALUE) .accept(MediaType.APPLICATION_JSON_UTF8_VALUE) .header("xxxxx", token) .content(jsonBody) // request body ).andExpect(status().isCeated()) .andReturn(); } }
HttpUtil.java类:
public class HttpUtil { public static HttpResponse doGet(String url, Map<String, String> params, Header[] headers) { ..... 这里省略 } }
好了,后续内容逐步添加。