spring中mock RestTemplate和FeignClient(mock方法內部的方法呼叫)
阿新 • • 發佈:2018-12-07
目的
要測試ServiceImpl類中的方法methodA
難點
methodA中呼叫了restTemplate的方法或者FeignClient的方法,而這兩個方法都依賴第三方應用,如果第三方應用沒有準備好,則會報錯,為了在單元測試中不依賴第三方應用,因此需要mock他們。
引入包
spring的這個jar包下自帶Mock相關內容。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</ artifactId>
<scope>test</scope>
</dependency>
FeignClient介面類
@FeignClient("applicationName")
public interface XXXClient extends XXXService{
}
測試類
注意:service如果是介面,要使用實現類ServiceImpl 來InjectMocks才行
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
@Mock
RestTemplate restTemplate;
@Mock
XXXClient client;
@InjectMocks
ServiceImpl serviceImpl;
@Test
public void test() throws Exception {
serviceImpl.methodA();
}
參考
https://stackoverflow.com/questions/42406625/how-to-mock-resttemplate-in-java-spring/42428738
https://zhuanlan.zhihu.com/p/21444517
https://www.jianshu.com/p/dcc12f06e807