单元测试查询
我必须测试几个类的功能,通过它们的父类(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/