使用mock构建http的post请求

1.引入依赖

<dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.18.0-GA</version>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-core</artifactId>
			<version>1.10.19</version>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-api-mockito</artifactId>
			<version>1.7.0</version>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.mockito</groupId>
					<artifactId>mockito-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-module-junit4</artifactId>
			<version>1.7.0</version>
			<scope>test</scope>
		</dependency>

2.在测试类上加注解

@WebAppConfiguration
@SpringBootTest
@RunWith(SpringRunner.class)

3.引入mock,注入web上下文

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext context;


    @Before
    public void before() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
    }

4.构建post请求

Cookie cookie = new Cookie(“key”,"value");//cookie值
HashMap<String, String> map = new HashMap<>();
map.put("param", "1213218");
this.mockMvc
                .perform(MockMvcRequestBuilders.post("/your/url")
                        .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
                        .cookie(cookie)
                        .content(JSONObject.toJSONString(map))

版权声明:本文为weixin_45307431原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。