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); }