在单元测试中实例化应用程序 class

Instancing the Application class in Unit Tests

我正尝试在 Android 项目上编写单元测试,但是 运行 遇到了创建应用程序 class 实例的障碍。该项目使用 Retrofit 和 LiveData 以及 Android 架构组件。

目前,我正在尝试测试 AuthRepositorylogin 函数,但我无法创建存储库的实例因为它依赖于自定义 SharedPrefs class,而自定义 Application class.

AuthRepository

@Singleton
class AuthRepository @Inject constructor(
    val retrofitService: RetrofitService,
    val sessionData: SharedPrefs
) {

    fun login(username: String, password: String): LiveData<LoginResponse> {

        return getCSRF().then {
            if (it.result is GenericResponse.ErrorType) {
                // Error Accepting Terms
                val mutableLiveData = MutableLiveData<LoginResponse>()
                mutableLiveData.value = LoginResponse(listOf(LoginResponse.ErrorType.Generic()))
                mutableLiveData
            }
            else {
                retrofitService.postLogin(LoginBody(username, password))
                    .map {
                        val res = LoginRemote.parseResponse(it.response)
                        return res
                    }
            }
        }
    }
}

SharedPrefs

class SharedPrefs @Inject constructor(context: Application) {

    private val sharedPrefs = context.getSharedPreferences("com.company.project.domain.PREFERENCE_FILE_KEY", Context.MODE_PRIVATE)

    private val PREF_KEY_SESSION_COOKIE = "sessionCookie"

    // SharedPreference Variable Management
    var sessionCookie: String
    get() = sharedPrefs.getString(PREF_KEY_SESSION_COOKIE, "")
    set(value) = saveString(PREF_KEY_SESSION_COOKIE, value)

}

以这种方式设置后,我可以 运行 为我的 AuthRepository 使用普通的旧单元测试吗?还是对 Application 的依赖会迫使我使用 Instrumentation Tests 来测试我的 AuthRepository?

1.You 可以使用 Mockito 模拟 Application class:

@Mock private lateinit var context: Application

@Before fun setupTasksViewModel() {
    MockitoAnnotations.initMocks(this)
}
  1. 或模拟SharedPrefs对象

    @Mock private lateinit var prefs: SharedPrefs