mock单元测试理解1--json转对象,spy调用真实方法,ReflectionTestUtils 设置属性,打桩redis

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
        </dependency>

  

1.在单元测试中,如果打桩时希望返回json中配置的文件,可以调用此方法;

List<OldSmsOrder> oldSmsOrders = JsonUtils.parseArrayFromFile("src/test/resources/db.json", OldSmsOrder.class);

这个方法时将json文件,转为对象list

 

2.比如,我想使用mock走调用钉钉接口的真实方法,而@mock只能配合打桩使用。这是可以使用@Spy,这个可以走真实方法。如

但是当走进真实方法时,会出现一个问题---appket和appSecret是从yml文件中读取的,也就是需要走spring容器,而mock是不走容器的。这时使用 ReflectionTestUtils 设置字段值;

这样走入getAccessToken的真实方法,appket和appSecre也会有值的;

 打桩redis

@Mock
private ValueOperations<String,String> valueOperations;
when(stringRedisTemplate.opsForValue()).thenReturn(valueOperations);
//redis value为空的情况
when(valueOperations.get(redisKeyYear)).thenReturn(null);

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

仅供参考

 

posted @ 2025-02-06 16:01  每月工资一万八  阅读(36)  评论(0)    收藏  举报