一、需求
在微服务框架模式下,往往需要在外部服务没有准备好的情况下进行测试。本文主要是讨论在SpringCloud体系下,以FeignClient进行通信时,对其进行mock的方式。
二、调用模型
微服务B通过FeignClient依赖其他服务调用。
三、构建方式
3.1)构建基础测试类
@RunWith(SpringRunner.class)
@ActiveProfiles(profiles = {"dev"})
@SpringBootTest(classes = BaseTest.class)
@ComponentScan("com.csdn.service")
@WebAppConfiguration
@AutoConfigureMockMvc
public class BaseTest {
}
3.2)Mock FeignClient
public class ServiceTest extends BaseTest {
@Resource
private ServiceB serviceB;
private ServiceFeign serviceFeign;
private String email;
@Before
public void setup() throws NoSuchFieldException, IllegalAccessException {
this.email = "mock@hupspot.com";
serviceFeign = Mockito.mock(ServiceFeign.class);
Field agentFeignClient = ServiceB.class.getDeclaredField("serviceFeign");
agentFeignClient.setAccessible(true);
agentFeignClient.set(serviceB, this.serviceFeign);
CommonResult<Objejct> res = CommonResult.success(new Object());
Mockito.when(serviceFeign.query(this.email)).thenReturn(res);
}
@Test
public void remoteFuncTest() {
String res = serviceFeign.remoteFunc(this.email);
Assert.assertEquals(String.join("_", this.email, this.email), res);
System.out.println("res=" + res);
}
}
主要就是初始化feignClient的方式(仅仅mock是没法注入到ServiceB中并生效的):
Field agentFeignClient = ServiceB.class.getDeclaredField("serviceFeign");
agentFeignClient.setAccessible(true);
agentFeignClient.set(serviceB, this.serviceFeign);文章来源:https://www.toymoban.com/news/detail-520164.html
文章来源地址https://www.toymoban.com/news/detail-520164.html
到了这里,关于【Testing】基于Mockito的FeignClient单元测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!