2

我想测试在AsyncTask中执行的方法。我已经嘲笑了里面的所有方法。我有 -Robolectric AsyncTask回调

  1. 获取所有必需参数并执行新的AsyncTask()的静态方法executeOnExecutor();
  2. 在onPostExecute()我调用结果的回调。

为了测试我使用:

testCompile 'junit:junit:4.12' 
testCompile "org.robolectric:robolectric:3.2.2" 
testCompile "org.powermock:powermock-module-junit4:1.6.4" 
testCompile "org.powermock:powermock-module-junit4-rule:1.6.4" 
testCompile "org.powermock:powermock-api-mockito:1.6.4" 
testCompile "org.powermock:powermock-classloading-xstream:1.6.4" 

但回调不会被调用。例如:

@RunWith(RobolectricTestRunner.class) 
    @Config(constants = BuildConfig.class, sdk = 24, 
      application = StubApplicationClass.class) 
    @PowerMockIgnore({"org.mockito.", "android.*"}) 
    @PrepareForTest(BaseHttpClient.class) 

    @SuppressStaticInitializationFor("io.realm.internal.Util") 
    public class GetDataTest { 

     @Rule 
     public PowerMockRule rule = new PowerMockRule(); 
     .................................... 

     @Test 
     public void getDataTest() throws Exception { 
     System.out.println("started"); 
     BaseAsyncClient.doAsync(UserPublicDataTable, Actions, 
       list, new IHttpResponse<String>() { 
        @Override 
        public void httpResponse(@Nullable String response) { 
         assertNotNull(response); System.out.println("onPostExecute()"); 
        } 
       }); 
     System.out.println("finished"); 
    } 

onPostExecute - 从不打印。

当我打电话:

Robolectric.flushBackgroundThreadScheduler(); 

我收到异常:

java.lang.NullPointerException 
    at org.robolectric.Robolectric.getBackgroundThreadScheduler(Robolectric.java:193) 
    at org.robolectric.Robolectric.flushBackgroundThreadScheduler(Robolectric.java:200) 

如何测试的AsyncTask与robolectric,powermock?

更新

当我看到ShadowApplication.getInstance() == null,这就是为什么我收到NPE异常,当调用 'flushBackgroundThreadScheduler'。

我创建了custom runner to create custom application,但它仍然为空。

要解决NPE在应用程序迁移到:

testCompile "org.robolectric:robolectric:3.0" 

UPDATE:

当我在@Test创建的AsyncTask - 它的工作原理

new AsyncTask() { 
     @Override 
     protected Object doInBackground(Object[] params) { 
      System.out.println("empty async task"); 
      return null; 
     } 
    }.execute(); 
    ShadowApplication.runBackgroundTasks(); 
    Robolectric.flushBackgroundThreadScheduler(); 

所以问题时,任务与创建“静态'方法

回答

0

我设法解决这个问题有一点变通办法:

  1. 降级版本testCompile “org.robolectric:robolectric:3.0”
  2. 呼叫异步塔斯新AsyncTask.execute()
  3. 呼叫ShadowApplication.executeBackgroundTasks();
  4. 执行后台时睡眠Thread.sleep(1000);
  5. 执行foregroud任务,ShadowScheduler

不幸的是,这需要等到后台线程执行。我没有找到一种方法来替换main的背景线程。

最后,我从AsyncTask迁移到RxJava。 那里,默认的方法我用相同的线程执行替换线程池执行人:

compile 'io.reactivex.rxjava2:rxandroid:2.0.1' 
compile 'io.reactivex.rxjava2:rxjava:2.0.1' 
RxJavaPlugins.setIoSchedulerHandler(new Function<Scheduler, Scheduler>() { 
      @Override 
      public Scheduler apply(Scheduler scheduler) throws Exception { 
       return ImmediateThinScheduler.INSTANCE; 
      } 
     }); 

Schedulers.io()是线程池的执行者,我用同一个线程执行更换ImmediateThinScheduler.INSTANCE