| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- package com.zd.system.base;
- import com.alibaba.fastjson.JSON;
- import org.junit.jupiter.api.TestInstance;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- 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.http.HttpHeaders;
- import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
- import org.springframework.test.web.servlet.MockMvc;
- import org.springframework.util.Assert;
- import org.springframework.web.client.RestTemplate;
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.Map;
- /**
- * 测试controller 基类
- *
- * @Author: zhoupan
- * @Date: 2021/09/08/8:39
- * @Description:
- */
- //@ActiveProfiles("junittest")
- @TestInstance(TestInstance.Lifecycle.PER_CLASS)
- @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
- @AutoConfigureMockMvc
- public class BaseControllerTest extends AbstractTransactionalJUnit4SpringContextTests {
- protected final Logger log = LoggerFactory.getLogger(this.getClass());
- @Autowired
- public MockMvc mockMvc;
- private String bearer = "Bearer ";
- public static HttpHeaders httpHeaders = new HttpHeaders();
- /**
- * 登录
- *
- * @param username
- * @param password
- * @throws Exception
- */
- public void beforeAll(String username, String password, boolean f) throws Exception {
- //mockMve 没办法指定主机地址,所以这里改成手动请求
- // MvcResult mvcResult = mockMvc
- // .perform(MockMvcRequestBuilders.get("http://localhost:8080/code"))
- // .andReturn();
- //不再重复登录
- if (!f && httpHeaders.containsKey("Authorization")) {
- return;
- }
- RestTemplate restTemplate = new RestTemplate();
- //创建请求头
- String url = "http://localhost:8080/auth/login";
- Map<String, String> map = new HashMap<>(2);
- map.put("username", username);
- map.put("password", password);
- String body = restTemplate.postForEntity(url, map, String.class).getBody();
- Map<String, Object> parse = (Map<String, Object>) JSON.parse(body);
- Assert.isTrue(parse.get("code").toString().equals("200"), "登录失败:" + parse.get("msg"));
- //拿到token
- Map<String, String> data = (Map<String, String>) JSON.parse(parse.get("data").toString());
- httpHeaders.put("Authorization", Collections.singletonList(bearer + data.get("access_token")));
- //采用模拟方式-即不走网关
- httpHeaders.put("user_id", Collections.singletonList(data.get("user_id")));
- httpHeaders.put("username", Collections.singletonList(data.get("username")));
- }
- public void beforeAll(String username, String password) throws Exception {
- beforeAll(username, password, false);
- }
- }
|