我们如何从基类中检索接口并对其进行测试?

问题描述 投票:0回答:1

单元测试查询

我必须测试通过superclass处理的几个类的功能。

即:我们有一个扩展了CustomerInitialiserImpl的自定义类SpAsyncHandler,后者具有以下方法:protected executeAsync(ExecuteAsync executeAsync)(参数ExecuteAsync是一个接口,方法executeAsync的作用是运行该接口一个或多个异步线程中以特定顺序排列的方法)。

ExecuteAsync看起来如下:

public interface ExecuteAsync {
       void initApi();
       void doInBackground();
       void onPostExecute();
}

CustomerInitialiserImpl具有以下方法:

public void initialiseCustomer(int id) {
       executeAsync(new ExeuteAsync() {
/*here are instantiated the 3 overridden methods of the interface*/
       });
}

由于我不在乎SpAsyncHandler中完成的异步工作,因此它具有自己的测试,但是我需要测试接口的方法是否正确执行以及它们是否触发了预期的结果(例如通过post等正确的EventBus事件)。

我一直在尝试找到一种方法来获取测试类中的这些实例化接口,但似乎找不到解决方法。

我曾尝试使用PowerMockito来获取protected方法,看看是否可以返回interface,但没有成功。

此外,此接口还包括要模拟的某些特定api方法的实例化。关于如何进行以及是否可以进行的任何线索?我知道架构听起来并不理想。我该如何进行?

java android unit-testing superclass
1个回答
0
投票

我知道了,但是必须先转换为Kotlin。

[我使用Kotlin的委托,所以CustomerInitialiserImpl将实现SpAsyncHandler的接口,该接口通常会注入普通的SpAsyncHandlerImpl,但是在单元测试中,我会通过MockSpAsyncHandlerImpl设置委托, ,除其他外,只需在主线程上执行所有接口函数即可。传递模拟对象时,它就像是一种魅力!

© www.soinside.com 2019 - 2024. All rights reserved.