Unit Testing with Firebase

18,293

Solution 1

UPDATE 2020: "So far this year (2020), this problem seems to have been solved using a (beta, at the date of this comment) Firebase emulator: Build unit tests using Fb Emulators and Unit testing security rules with the Firebase Emulator Suite, at YouTube This is done locally in the developer's computer. – carloswm85"

I found this https://www.firebase.com/blog/2015-04-24-end-to-end-testing-firebase-server.html but the article is over a year old. I only scanned it, I'll give it a more thorough read in a bit.

Either way, we really need the equivalent of the local Google AppEngine Backend that you can run in Intellij (Android Studio). Testing cannot be an afterthought in 2016. Really hoping one of the awesome Firebase devs notices this thread and comments. Testing should be part of their official guides.

Solution 2

Here is my solution - hope this helps:

[Update] I've removed my prev. sample in favor of this one. It's simpler and shows the main essence

    public class TestFirebase extends AndroidTestCase {
        private static Logger logger = LoggerFactory.getLogger(TestFirebase.class);

        private CountDownLatch authSignal = null;
        private FirebaseAuth auth;

        @Override
        public void setUp() throws InterruptedException {
            authSignal = new CountDownLatch(1);
            Firebase.setAndroidContext(mContext); //initializeFireBase(context);

            auth = FirebaseAuth.getInstance();
            if(auth.getCurrentUser() == null) {
                auth.signInWithEmailAndPassword("[email protected]", "12345678").addOnCompleteListener(
                        new OnCompleteListener<AuthResult>() {

                            @Override
                            public void onComplete(@NonNull final Task<AuthResult> task) {

                                final AuthResult result = task.getResult();
                                final FirebaseUser user = result.getUser();
                                authSignal.countDown();
                            }
                        });
            } else {
                authSignal.countDown();
            }
            authSignal.await(10, TimeUnit.SECONDS);
        }

        @Override
        public void tearDown() throws Exception {
            super.tearDown();
            if(auth != null) {
                auth.signOut();
                auth = null;
            }
        }

        @Test
        public void testWrite() throws InterruptedException {
            final CountDownLatch writeSignal = new CountDownLatch(1);

            FirebaseDatabase database = FirebaseDatabase.getInstance();
            DatabaseReference myRef = database.getReference("message");

            myRef.setValue("Do you have data? You'll love Firebase. - 3")
                    .addOnCompleteListener(new OnCompleteListener<Void>() {

                        @Override
                        public void onComplete(@NonNull final Task<Void> task) {
                            writeSignal.countDown();
                        }
                    });

            writeSignal.await(10, TimeUnit.SECONDS);
        }
    }
Share:
18,293
Tom Finet
Author by

Tom Finet

Updated on June 03, 2022

Comments

  • Tom Finet
    Tom Finet about 2 years

    I am building an android app which uses Firebase as the back-end and an model, view, presenter architecture. However, the fact that Firebase is a cloud service complicates the automated testing in my android app. So far I have built most of the authentication system, but am unable to see how to implement unit tests for the Firebase code in my app. In terms of end to end testing I am also stuck.

    Since testing is fundamental to any android app and without it application developers can't be sure what they have implemented is functioning as expected, I can't really progress any further without automated tests.

    In conclusion, my question is:

    Generally, how do you implement Firebase automated testing in an android app?

    EDIT:

    As an example could someone unit test the following method?

    public void addUser(final String name, final String birthday,
                            final String email, final String password) {
            Firebase mUsersNode = Constants.mRef.child("users");
            final Firebase mSingleUser = mUsersNode.child(name);
            mSingleUser.runTransaction(new Transaction.Handler() {
                @Override
                public Transaction.Result doTransaction(MutableData mutableData) {
    
                    mSingleUser.child("birthday").setValue(birthday);
                    mSingleUser.child("email").setValue(email);
                    mSingleUser.child("password").setValue(password);
                    return Transaction.success(mutableData);
                }
    
                @Override
                public void onComplete(FirebaseError firebaseError, boolean b, DataSnapshot dataSnapshot) {
                    if(firebaseError != null) {
                            mSignUpPresenter.addUserFail(firebaseError);
                        } else {
                            mSignUpPresenter.addUserComplete();
                    }
                }
            });
        }