微服务如何实现单元测试
1、单元测试示例@RunWith(SpringRunner.class)@SpringBootTest(classes = ConsultationApplication.class)public class FollowUpPlanControllerTest {@Resourceprivate FollowUpPlanController planController;@Resourcepri
·
1、单元测试示例
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConsultationApplication.class)
public class FollowUpPlanControllerTest {
@Resource
private FollowUpPlanController planController;
@Resource
private FollowUpOrderServiceImpl followUpOrderService;
private MockMvc planMvc;
@MockBean
private BaseServiceClient baseServiceClient;
private static final String token = "7d4b94180c42492895758265ebc22d46";
@Before
public void setUp() {
planMvc = MockMvcBuilders.standaloneSetup(planController).build();
SysUser sysUser = new SysUser();
sysUser.setId(1L);
sysUser.setUserName("test");
sysUser.setOrgId(1L);
sysUser.setOrgName("测试机构");
doReturn(new CommonResult<>(sysUser)).when(baseServiceClient).getUserByToken(anyString(), anyString());
}
//添加随访计划(验证单次随访)
@Test
public void saveFollowUpPlan(){
RequestBuilder request;
request = post("/api/followUpPlan/saveOrUpdateFollowUpPlan")
.header("BASE_PC_TOKEN_HEADER",token)
.param("businessId", "1314497970783260672")
.param("patientName", 张三")
.param("followUpType", "1")
.param("visitWayKey", "FOLLOW_PHONE")
.param("visitWayValue", "电话")
.param("followUpDate", "2020-10-25 14:14:25")
.param("followUpFrequency", "1")
.param("frequencyUnit", "1");
try {
ResultActions resultActions = planMvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.jsonPath("$.status").value("1"));
MockHttpServletResponse response = resultActions.andReturn().getResponse();
response.setCharacterEncoding("UTF-8");
resultActions.andDo(print());
// 判断是否生成随访工单
String res = response.getContentAsString();
JSONObject jsonObject = JSON.parseObject(res); ;
Long id = Long.valueOf(jsonObject.getString("data"));
Map<String, Object> map = new HashMap<>();
map.put("businessId", id);
List<FollowUpOrder> list = followUpOrderService.getList(map);
Assert.assertNotNull(list);
Assert.assertEquals(1, list.size());
} catch (Exception e) {
Assert.fail(e.getMessage());
e.printStackTrace();
}
}
}
2、模拟远程服务
使用@MockBean注解实现模拟远程服务,并模拟返回数据
@MockBean
private BaseServiceClient baseServiceClient;
@Before
public void setUp() {
planMvc = MockMvcBuilders.standaloneSetup(planController).build();
SysUser sysUser = new SysUser();
sysUser.setId(1L);
sysUser.setUserName("test");
sysUser.setOrgId(1L);
sysUser.setOrgName("测试机构");
doReturn(new CommonResult<>(sysUser)).when(baseServiceClient).getUserByToken(anyString(), anyString());
}
更多推荐
已为社区贡献1条内容
所有评论(0)