我是靠谱客的博主 孤独日记本,这篇文章主要介绍通过lambda和mockito answer提升单元测试效率,现在分享给大家,希望可以做个参考。

背景

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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 = new SpringCloudService(restTemplate); SpringCloudFact springCloudFact = myServiceUnderTest.retrieveFact(EXISTING_VARIA); assertThat(springCloudFact, is(new SpringCloudFact(EXISTING_VARIA, "OK"))); } @Test public void serviceShouldReturnNothing() { RestTemplate restTemplate = mock(RestTemplate.class); when(restTemplate.getForEntity(FACT_URL, SpringCloudFactResponse.class, NON_EXISTING_HTTP_PARAMS)) .thenReturn(ERROR_RESPONSE); SpringCloudService myServiceUnderTest = new SpringCloudService(restTemplate); SpringCloudFact springCloudFact = myServiceUnderTest.retrieveFact(NON_EXISTING_VARIA); assertThat(springCloudFact, is(nullValue())); } @Test(expected = ResourceAccessException.class) public void serviceShouldPropagateException() { RestTemplate restTemplate = mock(RestTemplate.class); when(restTemplate.getForEntity(FACT_URL, SpringCloudFactResponse.class, BAD_HTTP_PARAMS)) .thenThrow(new ResourceAccessException("I/O error")); SpringCloudService myServiceUnderTest = new SpringCloudService(restTemplate); myServiceUnderTest.retrieveFact(BAD_VARIA); } }

从上面可以看出,单测代码不仅对RestTemplate有了强依赖,且有很多重复的地方。

优化方案

经过阅读说明文档,发现mockito除了常用的thenReturn、thenThrow方法,还有一个thenAnswer方法。这个方法通过接收参数,实现一个通用的接口,而这个通用接口基本上可以返回任何想要的东西。相比于常用的thenReturn、thenThrow方法(只返回固定的值),Answer可以计算返回值,也就是说它和Java 8新特性中的函数式接口java.util.function.Function的功能基本相同T answer(InvocationOnMock invocation) throws Throwable;,唯一不同可能也就是throws了吧。有了个这个方法,我们就可以进一步优化代码了:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class SpringCloudServiceStepOneTest { 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 BAD_VARIA = 99999999L; private static final Map<String, Long> BAD_HTTP_PARAMS = Collections.singletonMap("id", BAD_VARIA); private static final ResponseEntity<SpringCloudFactResponse> 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 = restEndpointShouldAnswer(GOOD_HTTP_PARAMS, (invocation) -> ITEM_RESPONSE); SpringCloudService myServiceUnderTest = new SpringCloudService(restTemplate); SpringCloudFact springCloudFact = myServiceUnderTest.retrieveFact(EXISTING_VARIA); assertThat(springCloudFact, is(new SpringCloudFact(EXISTING_VARIA, "OK"))); } @Test public void serviceShouldReturnNothing() { RestTemplate restTemplate = restEndpointShouldAnswer(NON_EXISTING_HTTP_PARAMS, (invocation -> ERROR_RESPONSE)); SpringCloudService myServiceUnderTest = new SpringCloudService(restTemplate); SpringCloudFact springCloudFact = myServiceUnderTest.retrieveFact(NON_EXISTING_VARIA); assertThat(springCloudFact, is(nullValue())); } @Test(expected = ResourceAccessException.class) public void serviceShouldPropagateException() { RestTemplate restTemplate = restEndpointShouldAnswer(BAD_HTTP_PARAMS, (invocation -> {throw new ResourceAccessException("I/O error");})); SpringCloudService myServiceUnderTest = new SpringCloudService(restTemplate); myServiceUnderTest.retrieveFact(BAD_VARIA); } private RestTemplate restEndpointShouldAnswer(Map<String, Long> httpParams, Answer<ResponseEntity<SpringCloudFactResponse>> response){ RestTemplate restTemplate = mock(RestTemplate.class); when(restTemplate.getForEntity(FACT_URL, SpringCloudFactResponse.class, httpParams)).thenAnswer(response); return restTemplate; } }

优化点:
* 可以直接看到HTTP参数与响应的对照关系
* 可以绕过处理逻辑,不需要URL,HTTP方法这些依赖
* 可以将RestTemplate的mock提取成一个通用的方法,单测代码依赖度更低

问题:
* 代码不优美,每个单测中都有RestTemplate

进一步优化

通过@Before解决上述问题:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class SpringCloudServiceStepTwoTest { 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 BAD_VARIA = 99999999L; private static final Map<String, Long> BAD_HTTP_PARAMS = Collections.singletonMap("id", BAD_VARIA); private static final ResponseEntity<SpringCloudFactResponse> 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); private RestTemplate restTemplate; private SpringCloudService myServiceUnderTest; @Before public void setUp(){ restTemplate = mock(RestTemplate.class); myServiceUnderTest = new SpringCloudService(restTemplate); } @Test public void serviceShouldReturnFact() { restEndpointShouldAnswer(GOOD_HTTP_PARAMS, (invocation) -> ITEM_RESPONSE); SpringCloudFact springCloudFact = myServiceUnderTest.retrieveFact(EXISTING_VARIA); assertThat(springCloudFact, is(new SpringCloudFact(EXISTING_VARIA, "OK"))); } @Test public void serviceShouldReturnNothing() { restEndpointShouldAnswer(NON_EXISTING_HTTP_PARAMS, (invocation -> ERROR_RESPONSE)); SpringCloudFact springCloudFact = myServiceUnderTest.retrieveFact(NON_EXISTING_VARIA); assertThat(springCloudFact, is(nullValue())); } @Test(expected = ResourceAccessException.class) public void serviceShouldPropagateException() { restEndpointShouldAnswer(BAD_HTTP_PARAMS, (invocation -> {throw new ResourceAccessException("I/O error");})); myServiceUnderTest.retrieveFact(BAD_VARIA); } private void restEndpointShouldAnswer(Map<String, Long> httpParams, Answer<ResponseEntity<SpringCloudFactResponse>> response){ when(restTemplate.getForEntity(FACT_URL, SpringCloudFactResponse.class, httpParams)).thenAnswer(response); } }

总结

thenAnswer+lambda的方法虽然不是通用所有的case,但还是能解决大部分的单测依赖度高与代码重复较高的问题,根据说明文档,还有restEndpointShouldAnswer这个方法应该可以更进一步简化代码。无论采用什么方法,核心的思想就是AIR(Automatic, Independent, Repeatable)原则,保证了这个原则,才是高质量的单测代码。

参考资料

Answer (Mockito 2.15.0 API) - Javadoc.IO

最后

以上就是孤独日记本最近收集整理的关于通过lambda和mockito answer提升单元测试效率的全部内容,更多相关通过lambda和mockito内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部