getting NullPointerException when testing fragment using Robolectric in android

Viewed 62

i am a newbie to testing android apps. i am trying to test a login fragment which has email, password fields and login button. here is the test code->

@RunWith(RobolectricTestRunner::class)
class LoginSuccessTest {

    private lateinit var navigation: AppNavigationImpl

    @Before
    fun setupTestEnvironment() {
        navigation = mock(AppNavigationImpl::class.java)

        FirebaseApp.initializeApp(getApplicationContext())
    }

    @Test
    fun loginSuccess() {

        val activity: MainActivity = Robolectric.setupActivity(MainActivity::class.java)


        val email = "abc@gmail.com"
        val password = "abctest123"


//i get error here in the below line
        activity.findViewById<TextInputEditText>(R.id.emailEt).setText(email)
        activity.findViewById<TextInputEditText>(R.id.passwordEt).setText(password)

        activity.findViewById<TextView>(R.id.login).performClick()

        activity.appNavigation = navigation
        verify(navigation).showDashboardScreen()


    }

}

when i click on button i am supposed to be redirected to dashboard page. but when i run this test i get following error->

java.lang.NullPointerException
    at com.example.android.LoginSuccessTest.loginSuccess(LoginSuccessTest.kt:70)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.robolectric.RobolectricTestRunner$HelperTestRunner$1.evaluate(RobolectricTestRunner.java:570)
    at org.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:278)
    at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:834)

can someone help with whats going on? code is written in kotlin.

0 Answers
Related