asynchronous - How to test a Firebase task on Android? -
now trying test using junit4, getting
java.lang.illegalstateexception: must not called on main application thread @ com.google.android.gms.common.internal.zzab.zzhj(unknown source) @ com.google.android.gms.common.internal.zzab.zzate(unknown source) @ com.google.android.gms.tasks.tasks.await(unknown source) @ com.example.tasks.getuserprofiletest.then(getuserprofiletest.java:18) <27 internal calls> process finished exit code 255
i've created continuation task performs operation on firebase realtime database.
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(); } }
and unit test it:
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(), "john.connor@email.com"); } catch (executionexception e) { fail(e.getmessage()); } catch (interruptedexception e) { fail(e.getmessage()); } } }
is there simple way of testing tasks without using handlers or countdownlatch
?
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(), "john.connor@email.com"); } catch (executionexception e) { fail(e.getmessage()); } catch (interruptedexception e) { fail(e.getmessage()); } } }
Comments
Post a Comment