1

I am developing an Android application using Kotlin. I am adding instrumented tests into my project. Now, I am looking for a way to enable/disable the logic for launching activity because it can make my test behaving in unexpected ways.

This is my test class

@RunWith(AndroidJUnit4::class)
class LoginFormTest {
    @Rule @JvmField
    val loginActivityRule: ActivityTestRule<LoginActivity> = ActivityTestRule<LoginActivity>(LoginActivity::class.java)

    @Before
    fun setUp() {
    }

    @Test
    fun loginFormRendersErrorMessageWhenRequestThrowsError() {
        //logic
    }
}

That is just the signature of the test class. As you can see in the code, I am testing LoginActivity. LoginAcitivy is starting another activity when a button is clicked. Is there a way to disable activity from being started in the test. Then in another test method, I might enable it again. Is there a way to do that?

Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

1 Answers1

1

One can use the ActivityTestRule in order to setup the launch Intent ...

and then let the LoginActivity behave differently, eg. based upon the Intent action.

However, despite this is technically possible, this might not be the suggested approach.

Not clicking the button would eliminate the demand to adjust the application code.

In every case, you won't be able to change the debug APK from within a test APK.


A less intrusive way might be something alike:

private boolean shouldNavigate = true;

@VisisbleForTesting
public void setShouldNavigate(boolean value) {
    this.shouldNavigate = value;
}

So that you can enable/disable this from within the test class. With annotation @VisisbleForTesting, this will not pollute the public API, because .setShouldNavigate() is only visible when testing.

Martin Zeitler
  • 1
  • 19
  • 155
  • 216