java - 我们如何从基类中检索接口(interface)并测试它?

标签 java android unit-testing superclass

单元测试查询

我必须测试几个类的功能,通过它们的父类(super class)处理。

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

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中完成的异步工作,它有自己的测试,但是我需要测试接口(interface)的方法是否正确执行以及它们是否触发预期结果(例如通过 EventBus 等正确的 post 事件)。

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

我尝试使用PowerMockito来获取protected方法并查看是否可以返回接口(interface),但没有成功。

此外,此接口(interface)还包括一些要模拟的特定 api 方法的实例化。关于我如何继续以及是否可以做到这一点有任何线索吗?我知道这个架构听起来并不理想。我该如何继续?

最佳答案

我已经弄清楚了,但必须先转换为 Kotlin。

我使用了 Kotlin 的委托(delegate),因此 CustomerInitialiserImpl 将实现 SpAsyncHandler 的接口(interface),该接口(interface)通常会注入(inject)普通的 SpAsyncHandlerImpl,但是在在单元测试中,我将通过 MockSpAsyncHandlerImpl 设置委托(delegate),除其他外,它仅在主线程上执行所有接口(interface)函数。传递模拟对象,它就像一个魅力!

关于java - 我们如何从基类中检索接口(interface)并测试它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57312186/

相关文章:

c# - 如何在 Android 中使用信号器

c# - 人们如何使用 Entity Framework 6 进行单元测试,你应该打扰吗?

java - Spring RowMapper

java - 使用ctrl+z退出java程序?

java - 我可以在 Java 中公开 protected 成员吗?我想从子类访问它

java - 将 Double 的 ArrayList 转换为 double[]

android - 文本与设计中提到的图像对齐 - Android

android - 获取弹窗的度量

Silverlight MVVM 单元测试说明

unit-testing - 如何在 VueJS 中测试计算属性?