Search code examples
androidunit-testingjunit4account

JUnit test can't create an Account


I'm trying to run some test in my app, but when I try to create an Account(name, type) the result is always null in JUnit but working properly when I run the app

Example:

class ExampleTest {

@Rule
@JvmField
val instantExecutorRule = InstantTaskExecutorRule()
@Rule
@JvmField
val trampolineSchedulerRule = TrampolineSchedulerRule()

val ACCOUNT_NAME = "ACCOUNT_NAME"
val ACCOUNT_TYPE = "ACCOUNT_TYPE"

@Test
fun createAccountTest() {
    val account = Account(ACCOUNT_NAME, ACCOUNT_TYPE)

    assertThat(account.name, `is`(ACCOUNT_NAME))
}
}

Is there any special way to create an Account when I run test?


Solution

  • I think your problem is that you are trying to perform this type of test in the test directory, which is the one for unit tests.

    In this case you are accessing a framework class so you need to put the test in your androidTest directory where reside the instrumented tests.

    In my environment this test is green:

    import org.junit.Assert.assertEquals
    import org.junit.Assert.assertNotEquals
    
    @RunWith(AndroidJUnit4::class)
    class AccountTest {
    
        @Test
        fun accountCreationTest() {
            val account = Account("NAME", "TYPE")
            assertEquals(account.name, "NAME")
            assertNotEquals(account.name, "WRONGNAME")
        }
    
    }