## 介紹
微服務有單元測試同樣是使用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);
}
}
```