我正在尝试在单元测试中测试我的改造类,我面临着将依赖项注入我的测试类的问题。我有 3 节课:
- 服务类:改造接口
- 使用 Room 的数据库类(需要应用程序上下文)
- 使用服务和数据库构建的存储库
这是存储库代码:
class Repository(
private val database: Database,
private val service: Service
)
{
fun login(credentials: String): LiveData<String> {
val loginResponse = MutableLiveData<String>()
service.login(credentials)
.enqueue(object: Callback<ResponseBody>{
// Login SUCCESS
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (response.isSuccessful)
loginResponse.value = response.body()?.string()
else
loginResponse.value = response.errorBody()?.string()
}
// Login FAILED
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
loginResponse.value = t.message
}
})
return loginResponse
}
}
这是我的测试课:
@RunWith(AndroidJUnit4::class)
class ApiTest: KodeinAware {
private val instrumentationContext = InstrumentationRegistry.getInstrumentation().context
override val kodein = Kodein {
// Define injections
bind() from singleton { Service() }
bind() from singleton { Database(instrumentationContext) }
bind() from singleton { Repository(instance(), instance()) }
}
private val repository: Repository by instance()
@Test
fun login_isSuccessful() {
val loginResponse = repository.login("xxxxxxxxx")
val response = "{................}"
assertEquals(loginResponse, response)
}
我收到以下错误:
E/TestRunner: java.lang.IllegalArgumentException: Cannot provide null context for the database.