## 介绍
微服务有单元测试同样是使用JUnit+Mockito,通常对Feign接口构造一个Mock对象模拟调用。
## feign远程调用
* Service方法
```
// service方法中通过helloRemote调用了一个远程服务
@Service
public class ConsumerService {
@Autowired
HelloRemote helloRemote;
public String helloRemote(@PathVariable("name") String name) {
System.out.println("其他业务逻辑");
String hello = helloRemote.hello(name);
System.out.println("其他业务逻辑");
return hello;
}
}
```
* Feign接口
```
// feign接口
@FeignClient(name="service-producer",fallback=HelloRemoteFallback.class)
public interface HelloRemote {
@RequestMapping(value="/hello")
String hello(@RequestParam(value = "name") String name);
}
```
* 单元测试示例
```
@RunWith(MockitoJUnitRunner.class)
public class MockFeignTest {
@InjectMocks
ConsumerService consumerService;
@Mock
HelloRemote helloRemote;
@Test
public void test() {
String name = "hulu";
String mockResult = "hello hulu, this is fallback";
when(helloRemote.hello(name)).thenReturn(mockResult);
// 真实调用service方法
String result = consumerService.helloRemote(name);
//最后这里加上断言,进行判断执行结果是否达到我们的预期
assertEquals(mockResult,result);
}
}
~~~
```
## redis访问
分布式系统中redis是最常用的中央缓存,以下是对redis的mock过程。
* Service方法
```
@Service
public class ConsumerService {
// 这里直接使用redisTemplate操作redis,实际项目中可能会再封装一层
@Autowired
private RedisTemplate<String, String> redisTemplate;
public String helloRedis(String key){
System.out.println("调用redis前的业务逻辑……");
String result = redisTemplate.opsForValue().get(key);
System.out.println("调用redis后的业务逻辑……");
return result;
}
}
```
* 单元测试示例
```
@RunWith(MockitoJUnitRunner.class)
public class RedisTest {
@InjectMocks
ConsumerService consumerService;
@Mock
private RedisTemplate<String, String> redisTemplate;
@Test
public void test() {
String key = "test";
// 对redisTemplate.opsForValue().get("key")进行mock 这也是一个级联方法的mock
ValueOperations valueOperations = mock(ValueOperations.class);
when(redisTemplate.opsForValue()).thenReturn(valueOperations);
when(valueOperations.get("test")).thenReturn("this is mock redis");
// 真实调用service方法
String result = consumerService.helloRedis(key);
//最后这里加上断言,进行判断执行结果是否达到我们的预期
assertEquals("this is mock redis",result);
}
}
```