2016-11-17 4 views
3

は今、私はJUnit4を使ってそれをテストしようとしていますが、私はFirebase Realtime Database上で操作を実行Continuationタスクを作成しましたAndroidでFirebaseタスクをテストする方法は?

java.lang.IllegalStateException: 
    Must not be called on the main application thread 

at com.google.android.gms.common.internal.zzab.zzhj(Unknown Source) 
at com.google.android.gms.common.internal.zzab.zzate(Unknown Source) 
at com.google.android.gms.tasks.Tasks.await(Unknown Source) 
at com.example.tasks.GetUserProfileTest.then(GetUserProfileTest.java:18) 
    <27 internal calls> 

Process finished with exit code 255 

を取得しています。そのため

public class GetUserProfile implements Continuation<String, Task<Profile>>, 
     ValueEventListener { 

    private TaskCompletionSource<Profile> mTaskCompletionSource; 
    private DatabaseReference mDatabase; 

    public GetUserProfile() { 
     mTaskCompletionSource = new TaskCompletionSource(); 
     mDatabase = FirebaseDatabase.getInstance().getReference(); 
    } 

    @Override 
    public void onCancelled(DatabaseError databaseError) { 
     mDatabase.removeEventListener(this); 
     mTaskCompletionSource.setException(databaseError.toException()); 
    } 

    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 
     mDatabase.removeEventListener(this); 
     mTaskCompletionSource.setResult(dataSnapshot.getValue(Profile.class)); 
    } 

    @Override 
    public Task<Profile> then(Task<String> task) { 
     mDatabase.child(task.getResult()).addValueEventListener(this); 
     return mTaskCompletionSource.getTask(); 
    } 
} 

とユニットテスト:

public class GetUserProfileTest { 
    @Test 
    public void then() throws Exception { 
     Task<Profile> task = Tasks.<String>forResult("17354686546") 
      .continueWithTask(new GetUserProfile()); 

     try { 
      Profile profile = Tasks.await(task); 
      assertEquals(profile.getEmail(), "[email protected]"); 
     } catch (ExecutionException e) { 
      fail(e.getMessage()); 
     } catch (InterruptedException e) { 
      fail(e.getMessage()); 
     } 
    } 
} 

handlersまたはCountDownLatchを使用せずにテスト作業の簡単な方法はありますか?

+0

どのラインがエラーの原因となっていますか、その完全なスタックトレースは何ですか? –

+0

'Tasks.await'はメインスレッドをブロックしているためです。私はそれが 'CountDownLatch'を使って実行できることを知っていますが、より洗練された解決法を見つけるために飛び回っていました。 –

+1

私は単にContinuationの 'then'メソッドを直接呼び出します。また、真の単体テストであるために、私はデータベース全体を模擬して、それが正しく相談されたことを確認するだけです。しかし、単体テストが本当にスレッディングをテストしなければならない場合(CDLがそうでない方が良い)、CDLが使えます。 –

答えて

0
public class GetUserProfileTest { 
    @Test 
    public void then() throws Exception { 
     try { 
      Task<String> previousTask = Tasks.forResult("17354686546"); 
      GetUserProfile continuation = new GetUserProfile(); 
      Profile profile = continuation 
        .then(previousTask) 
        .getResult(); 

      assertEquals(profile.getEmail(), "[email protected]"); 
     } catch (ExecutionException e) { 
      fail(e.getMessage()); 
     } catch (InterruptedException e) { 
      fail(e.getMessage()); 
     } 
    } 
} 
関連する問題