@RunWith(SpringRunner.class)
@SpringBootTest(classes={TestApplication.class}) //Springboot启动类
@Component //Junit必须设置此注解
@Slf4j
class MifMemberControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext applicationContext;
@Autowired
private MifMemberController mifMemberController;
@Autowired
private AppController appController;
@Getter
@Setter
private String token;
/**
* 1 初始化Mock
* 2 获取用户的token
*/
@BeforeEach //junit5注解
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();
//先获取短信验证码
AppSmsDTO appSmsDTO = new AppSmsDTO();
appSmsDTO.setExist(true);
appSmsDTO.setPhone("135111111111");
appController.sendProfileSmsCode(appSmsDTO);
//再执行登录操作
LoginDto loginDto = new LoginDto();
loginDto.setPhone(Base64.getEncoder().encodeToString("135111111111".getBytes()));
loginDto.setCode(Base64.getEncoder().encodeToString("123456".getBytes()));//模拟短信验证码
R<Map<String, Object>> tt= appController.phoneLogin(loginDto);
Map<String, Object> dataMap= tt.getData();
this.setToken(dataMap.get("token").toString());
log.warn("token = " + this.token);
}
@SneakyThrows
@Test
public void getMemberEx() {
SearchDto searchDto = new SearchDto();
searchDto.setSize(10L);
searchDto.setCurrent(1L);
mockMvc.perform(
MockMvcRequestBuilders.post("/mifmember/getMemberEx")
.content(JSONObject.toJSONString(searchDto))
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.header("token",this.token)
)
.andDo(print())
.andExpect(MockMvcResultMatchers.status().isOk());
}
@Test
@SneakyThrows
public void currentMemberId() {
log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
mockMvc.perform(
MockMvcRequestBuilders.post("/mifmember/currentMemberId")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.header("token",this.token)
)
.andDo(print())
.andExpect(MockMvcResultMatchers.status().isOk());
log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
}
}
SpringCloud 微服务Junit测试(Controller层) 包含Fegin调用远程服务(本机调用开发环境机器上部署的微服务)
于 2023-08-16 13:45:01 首次发布