步骤:
前言
有很多同学喜欢用@springbootTest这个注解来写单元测试,在我看来这是不好的,因为这个注解会把我们的项目都启动一遍,包括会去做一些链接数据库啊,甚至是执行数据库的操作(如果我们写到初始化的方法里面),站在一个开发者的角度是不知道别的开发者会做一些什么操作,我认为这是危险的。而且启动这个项目会耗时比较长,这会影响到我们写单元测试的效率。单元测试也不需要真正的操作数据库的。所以用@RunWith(SpringJUnit4ClassRunner.class)来写就好了,简单轻便。
1,测试类上打注解@RunWith(SpringJUnit4ClassRunner.class)
2,mock对象
@MockBean mock不需要执行进去的对象
@SpyBean 需要执行进去的对象
@Before
public void before() {
}
before方法可以用来初始化一些操作,比如我们要读取配置文件的config对象,我们可以自己来给他设置值
3,测试方法上打注解@Test
String param = ”xxx“;
ParamDto paramDto = JSON.parseObject(param, ParamDto.class);
得到一个mock的泛型List:
List<InfoPO> infos = JSONObject.parseArray(string, InfoPO.class);
JSON,是fastjson,版本1.2.60。然后向上面那样来得到一个我们要测试方法的入参
Mockito.when(XXX).thenReturn(response);
Mockito来给我们测试方法中的 不需要进去的方法打桩stub.其实就是mock一个返回值,执行到的时候就直接返回我们设定好的值
4,调用测试的方法
比如
flowService.test();
flowService是需要用@SpyBean来mock的。
5,org.junit下的Assert类来比较返回的是否符合我们预期。这样就完成了一个简单的单元测试。
补充:
对restTemplate.exchange进行mock,这里很不好mock,因为比较难匹配上参数,只有参数匹配到了才会返回我们实现设置好的结果。
public ResponseEntity<String> commonCall(String remoteUrl, HttpMethod httpMethod, Map<String, Object> paramsMap, HttpHeaders headers){
ResponseEntity<String> responseEntity;
try{
HttpEntity<String> entity = new HttpEntity<>(JSON.toJSONString(paramsMap), headers);
responseEntity = restTemplate.exchange(remoteUrl , httpMethod, entity, String.class);
} catch (HttpStatusCodeException e){
//for 4XX,5XX from BRE,this HttpStatusCodeException can obtain error message rather t
// han Exception
throw new BusinessException(e.getResponseBodyAsString());
} catch (Exception e){
throw new BusinessException(e.getMessage());
}
return responseEntity;
}
我们需要像下面这样mock就可以返回我们想要的结果了。经过我的测试有效。
ResponseEntity responseEntity = new ResponseEntity(HttpStatus.OK);
Mockito.when(restTemplate.exchange( Matchers.anyString(),
Matchers.any(HttpMethod.class),
Matchers.<HttpEntity<?>> any(),
Matchers.<Class<String>> any())).thenReturn(responseEntity);
注意:
在我们平时写代码中功用的对象尽量不要去new,因为这样会导致我们在写单元测试时没法去mock对象,比如你这样使用restemplate
private RestTemplate createRestTemplate() {
return new RestTemplate();
}
这是我们没有办法去mock一个restemplate的,new出来的restemplate,会真正去请求参数里的url,这样会跟环境有依赖,这样明显不合理,单元测试只是测试代码逻辑。