AsyncTask的测试不执行 [英] asyncTask test doesn't execute

查看:1088
本文介绍了AsyncTask的测试不执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用robolectric测试我的AsyncTask类。在测试它做什么,我希望当任务运行,像这样:

I'm using robolectric to test my AsyncTask class. In the test it does what I expect when the task is run like so:

asyncTask.execute()

但是当我做

asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)

它没有(在这两种情况下我跑

it doesn't (in both instances I run

Robolectric.runUiThreadTasksIncludingDelayedTasks()

任何人有任何想法,为什么叫executeOnExecutor不会触发Robolectric运行,但执行工作正常?

Anyone have any idea why calling executeOnExecutor doesn't trigger Robolectric to run but execute works fine?

推荐答案

该Robolectric框架不能开箱即用的默认工作执行人(即无论是AsyncTask.THREAD_POOL_EXECUTOR或AsyncTask.SERIAL_EXECUTOR),也不能与自定义的。

The Robolectric framework cannot work out of the box with the default executors (i.e. either AsyncTask.THREAD_POOL_EXECUTOR or AsyncTask.SERIAL_EXECUTOR), nor with custom ones.

为了解决这个问题,你可以采取这两种方法之一,具体取决于你是否有过测试单元采用执行人控制。如果答案是YES,第一种方法是简单地把它使用的 RoboExecutorService (或者如果使用的版本下3.0 - <一个href=\"http://robolectric.org/javadoc/2.4/org/robolectric/util/RobolectricBackgroundExecutorService.html\"相对=nofollow> RobolectricBackgroundExecutorService )。否则,你将不得不采取不同的方法这是应用此2步骤的解决方法:

To solve this issue, you can take one of these two approaches, depending of whether you have control over the executor the tested unit uses. If the answer is YES, the first approach would be to simply get it to use RoboExecutorService (or if using versions under 3.0 - RobolectricBackgroundExecutorService). Otherwise, you'll have to take a different approach which is to apply this 2-steps workaround:

您需要做的第一件事情就是实现一个自定义执行人覆盖执行一个的AsyncTask 阴影:

The first thing you need to do is to implement an AsyncTask shadow that overrides execution on custom executors:

@Implements(AsyncTask.class)
public class MyShadowAsyncTask<Params, Progress, Result> extends ShadowAsyncTask<Params, Progress, Result> {

    @Implementation
    public AsyncTask<Params, Progress, Result> executeOnExecutor(Executor executor, Params... params) {
        return super.execute(params);
    }       
}

注册自定义阴影

在每个测试用例运行的生产code,使用的AsyncTask#executeOnExecutor(),注册您的自定义阴影覆盖Robolectric的默认,这种方式(请查看配置'注释):

Registering the custom shadow

In each test case running production code that uses AsyncTask#executeOnExecutor(), register your custom shadow to override Robolectric's default, this way (review the 'config' annotation):

@RunWith(RobolectricTestRunner.class)
@Config(shadows={MyShadowAsyncTask.class})
public class MyTest {
    // ... test code
}

因之调用 Robolectric.runUiThreadTasks() Robolectric.runUiThreadTasksIncludingDelayedTasks()将工作如你所期望(即,将阻止亚军线程异步,直到任务完成)。

Consequent calls to Robolectric.runUiThreadTasks() or Robolectric.runUiThreadTasksIncludingDelayedTasks() would work as you'd expect (namely, would block the runner thread till async tasks complete).

这篇关于AsyncTask的测试不执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆