dubbo mock服务

1. jar包引入

<!-- mock -->
<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-module-junit4</artifactId>
   <version>1.7.0</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-api-mockito2</artifactId>
   <version>1.7.0</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-api-easymock</artifactId>
   <version>1.7.0</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.mockito</groupId>
   <artifactId>mockito-core</artifactId>
   <version>2.8.47</version>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>org.hamcrest</groupId>
   <artifactId>hamcrest-junit</artifactId>
   <version>2.0.0.0</version>
   <scope>test</scope>
</dependency>

2.  Mock服务的使用

@Bean
public AppAuthRegisterFacade appAuthRegisterFacade() {
    AppAuthRegisterFacade remoteApi = PowerMockito.mock(AppAuthRegisterFacade.class);
    String appId = "123";
    PowerMockito.when(remoteApi.queryAppAuthRegister(appId))
            .thenAnswer(t -> new AppAuthRegister());
    return remoteApi;
}

 其中AppAuthRegisterFacade为依赖的dubbo接口

queryAppAuthRegister为该接口的方法

appId为dubbo接口入参

上述代码代表实现了一个dubbo的mock实例, 当调用dubbo接口指定的方法时,会自动返回指定的Mock值

3. 注意点

 需要手动注入dubbo mock实例,否则会自动选择dubbo代理实例

@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class MockDubboTest {

    @Autowired
    private ApplicationContext applicationContext;
   
    @Autowired
    private AuthServiceImpl authServiceImpl;

    @Before
    public void before() {
        AuthServiceImpl authService = applicationContext.getBean(AuthServiceImpl.class);
        AppAuthRegisterFacade appAuthRegisterFacade = applicationContext.getBean(AppAuthRegisterFacade.class);
        AppAuthRegisterFacade appAuthRegisterFacade1 = appAuthRegisterFacade();
        System.out.println("appAuthRegisterFacade:"+appAuthRegisterFacade);
        System.out.println("appAuthRegisterFacade1:"+appAuthRegisterFacade1);
        System.out.println("authService:"+authService);
        authService.setAppAuthRegisterFacade(appAuthRegisterFacade1);
    }

服务调用 

@Bean
public AppAuthRegisterFacade appAuthRegisterFacade() {
    AppAuthRegisterFacade remoteApi = PowerMockito.mock(AppAuthRegisterFacade.class);
    String appId = "123";
    PowerMockito.when(remoteApi.queryAppAuthRegister(appId))
            .thenAnswer(t -> new AppAuthRegister());
    return remoteApi;
}

@Test
public void testQuery(){
    AppAuthRegister query = authServiceImpl.query("123");
    System.out.println(query);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值