【填坑】单元测试mockito时遇上when抛异常的问题
封装了 redisson,写单元测试时,踩了 mockito 中 when 的坑。
查了半天资料解决不了,脑子灵光一闪,原来是mock的对象,不能在初始化配置时赋值,正确的写法如下:
1 @Mock 2 private RedissonClient redissonClient; 3 4 @Before 5 public void init() { 6 String host = "192.168.0.1"; 7 Integer port = 1234; 8 String password = "KQxakrN1"; 9 Config config = new Config(); 10 config.useSingleServer() 11 .setAddress(host + ":" + port) 12 .setPassword(password.length() == 0 ? null : password); 13 RedissonClient tmpRedissonClient = Redisson.create(config); 14 RLock rg = tmpRedissonClient.getLock("test21721rlock"); 15 16 MockitoAnnotations.initMocks(this); 17 when(redissonClient.getLock(anyString())).thenReturn(rg); 18 19 redissonClient = tmpRedissonClient; 20 }