通过lambda和mockito answer提升单元测试效率

背景

在测试Spring RestTemplate的时候,为了规避上下文带来的影响且保证单元测试的效率与独立性,使用mock技术是常用的手法。但是实际项目中,如果要从RestTemplate转为其他框架的时候,就需要修改所有的单元测试代码,也就是说,目前的代码还是依赖于框架的,还是不够独立:

public class SpringCloudRefactoringTest {
   

    private static final Long EXISTING_VARIA = 1L;
    private static final Map<String, Long> GOOD_HTTP_PARAMS = Collections.singletonMap("id", EXISTING_VARIA);
    private static final Long NON_EXISTING_VARIA = 15123123L;
    private static final Map<String, Long> NON_EXISTING_HTTP_PARAMS = Collections.singletonMap("id", NON_EXISTING_VARIA);
    private static final Long OVER_VARIA = 99999999L;
    private static final Map<String, Long> BAD_HTTP_PARAMS = Collections.singletonMap("id", BAD_VARIA);

    private static final ResponseEntity<SpringCloudResponse> ERROR_RESPONSE =
            new ResponseEntity<>(new SpringCloudFactResponse("NoSuchQuoteException", "No quote with id=15123123."), HttpStatus.OK);
    private static final ResponseEntity<SpringCloudFactResponse> ITEM_RESPONSE =
            new ResponseEntity<>(new SpringCloudFactResponse("success", new SpringCloudFact(1L, "OK")), HttpStatus.OK);

    @Test
    public void serviceShouldReturnFact() {
        RestTemplate restTemplate = mock(RestTemplate.class);
        when(restTemplate.getForEntity(FACT_URL, SpringCloudFactResponse.class, GOOD_HTTP_PARAMS))
                .thenReturn(ITEM_RESPONSE);
        SpringCloudService myServiceUnderTest = 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值