简体   繁体   English

验证异步任务是否在robolectric 3上运行

[英]Verifying that async task run with robolectric 3

I have a method that starts couple of async tasks on background thread: 我有一个方法可以在后台线程上启动几个异步任务:

public void fetchSome() {
    new SomeTask1().execute();
    new SomeTask2().execute();
    new SomeTask3().execute();
}

How can I test that these three tasks are executed with Robolectric 3.0 . 如何测试这三个任务是用Robolectric 3.0执行的。

Before I would warn you that AsyncTask are not good solution for performing background operations. 在我警告您AsyncTask并不是执行后台操作的好解决方案之前。 Take a look to talks in internet what is so bad with AsyncTask . 看一下互联网上的对话,用AsyncTask什么不好的地方。

As for me you're trying to test too many things. 至于我,您正在尝试测试太多的东西。 I would split it. 我会分开的。

  1. Test that your code is starting async tasks: 测试您的代码是否正在启动异步任务:

    • Write a Factory class which will instantiate async tasks for you 编写一个Factory类,它将为您实例化异步任务
    • Mock factory in test and return mocks for tasks 模拟工厂进行测试并返回模拟任务
    • Check that execute for task happened 检查是否已执行任务
  2. Test that your tasks are doing right job: 测试您的任务是否做得正确:

    • Write test for every async task class 为每个异步任务类编写测试
    • mock dependencies and check that tasks are interacting with outside world correctly 模拟依赖关系,并检查任务是否与外界正确交互
  3. Test that your tasks update UI with result: 测试您的任务是否使用结果更新UI:

    • Introduce listeners 介绍听众
    • Mock them and pass to async tasks 模拟它们并传递给异步任务
    • Check that sync tasks calls them during final own lifecycle 检查同步任务在最终生命周期内是否调用了它们
    • Make UI implement listeners contract 使UI实现侦听器契约
    • Call in UI test listener methods 调用UI测试侦听器方法
    • Check that it is updated correctly with results 检查结果是否正确更新

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM