Booyaches
Booyaches

Reputation: 1719

Unresolved androidx classes for writing unit tests

I am trying to write my first test and I have problem figuring out the right dependencies to get everything to work. Here is my test class

class EmployeeDatabaseTest {
    private lateinit var employeeDao: EmployeeDAO

    @Before
    fun setup() {
        EmployeeDatabase.TEST_MODE = true
        employeeDao = EmployeeDatabase.getDatabase(??).employeeDao()
    }

    @Test
    fun should_Insert_Employee_Item() {
        val employee = Employee("xx", "xx", 31, Gender.MALE)
        employee.id = 1
        runBlocking {  employeeDao.addNewEmployee(employee) }
        val employeeTest = runBlocking {  getValue(employeeDao.getEmployeeById(employee.id!!)) }
        Assert.assertEquals(employee.name, employeeTest.name)
    }
}

Normally I would obtain context by InstrumentationRegistry.getContext()...but InstrumentationRegistry can't be resolved. It also can't resolve getValue(..) method. I am new to testing but I bet is something with dependencies. Here is my build.gradle:

dependencies {
   ...
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test:rules:1.2.0'
    androidTestImplementation 'org.hamcrest:hamcrest-library:1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
    androidTestImplementation 'androidx.test:core:1.2.0'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
}

defaultConfig {
    ...
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

Do I miss something I am I doing something wrong?

Upvotes: 0

Views: 623

Answers (1)

tynn
tynn

Reputation: 39853

A simple Context can be resolved with

androidx.test.core.app.ApplicationProvider.getApplicationContext()

which is part of the core module

androidTestImplementation 'androidx.test:core:1.2.0'

When you use Robolectric, you can also have it as

testImplementation 'androidx.test:core:1.2.0'

Upvotes: 1

Related Questions