JUnit testing on class with firebase

后端 未结 1 1005
感动是毒
感动是毒 2021-01-14 09:57

I\'m trying to JUnit test this class:

public class WeekListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
         


        
1条回答
  •  抹茶落季
    2021-01-14 10:36

    As usual, I suggest everybody to not mix presentation and storage code. And this is a question for another topic.

    And here the trick how you can achieve what you want. First, extract method for Firebase initialisation and providing FirebaseAuth:

     @VisibleForTest
     @NonNull
     FirebaseAuth initAndReturnFirebaseAuth() {
         FirebaseApp.initializeApp(this);
         FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
     }
    

    Second, create test activity and override this method:

    public class TestWeekListActivity extends WeekListActivity {
        @Override
        @NonNull
        FirebaseAuth initAndReturnFirebaseAuth() {
           FirebaseAuth authMock = mock(FirebaseAuth.class);
           when(authMock.getCurrentUser()).thenReturn(mockFirebaseUser);
           return authMock;
        }
    }
    

    And then use test activity in test instead of you real activity.

    Hope it helps!

    0 讨论(0)
提交回复
热议问题