0


【Testing】基于Mockito的FeignClient单元测试

一、需求

   在微服务框架模式下,往往需要在外部服务没有准备好的情况下进行测试。本文主要是讨论在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 = "[email protected]";
        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);

标签: 单元测试 java junit

本文转载自: https://blog.csdn.net/lavorange/article/details/126087871
版权归原作者 忆之独秀 所有, 如有侵权,请联系我们删除。

“【Testing】基于Mockito的FeignClient单元测试”的评论:

还没有评论