Search code examples
javaandroidkotlinjunit4android-espresso

@Before annotation being ignored by kotlin in espresso test?


I have this instrumented test class written in kotlin and uses espresso to execute the tests. When I run it though, the function annotated with @Before is being completely ignored. Even when debugging the test and placing a breakpoint in it, it wouldn't pass through that point. Do you have any idea why this happens? I've been searching in google but most examples don't use @Before or simply don't mention any problem with it. I also added the logOut() function for more information.

PD: writing the same code in java works perfectly.

@RunWith(AndroidJUnit4::class)

class LoginTest {

    @get: Rule val activityTestRule = ActivityTestRule(SplashActivity_::class.java)

    private lateinit var user: User

    @Before fun setUp() {
        logOut()
    }

    @Test fun newUserWasLoggedIn() {
        givenAnUser(UserFactory.randomUser)
        itCanBeLoggedAsNewUser()
    }

    @Test fun oldUserWasLoggedIn() {
        givenAnUser(UserFactory.oldUser)
        itCanBeLoggedAsOldUser()
    }

    private fun itCanBeLoggedAsOldUser() {
        oldUserLogin(user)
    }

    private fun itCanBeLoggedAsNewUser() {
        newUserLogin(user)
    }

    private fun givenAnUser(user: User) {
        this.user = user
    }
}

.

fun logOut() {
    goToSettingsView()
    settingsView {
        swipe(SwipeDirection.UP)
        logOutButton.click()
        if (isPasswordRequired()) {
            createNewPasswordInDialog()
            logOutButton.click()
        }
        buttonAccept.click()
    }
}

Solution

  • The problem was due to code obfuscation. In this case, as we wanted the variant for automation to be as close as possible to release, the obfuscation was added to the build variant used for automated tests. The solution was adding a proguard-test-rules.pro file for tests with the following lines:

    -ignorewarnings
    -keepattributes *Annotation*
    -dontnote junit.framework.**
    -dontnote junit.runner.**
    -dontwarn android.test.**
    -dontwarn android.support.test.**
    -dontwarn org.junit.**
    -dontwarn org.hamcrest.**
    -dontwarn com.squareup.javawriter.JavaWriter
    -keep class path.to.tests.*
    

    and add to the build variant in build.gradle:

    testProguardFile 'proguard-test-rules.pro'