[FIXED] Instancing the Application class in Unit Tests

Issue

I am attempting to write Unit Tests on an Android project, but have run into a roadblock with creating an instance of the Application class. The project uses Retrofit and LiveData with Android Architecture Components.

Currently, I am trying to test my AuthRepository ‘s login function, but I can’t create an instance of the repository because it is dependent on a custom SharedPrefs class which is dependent on a 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)

}

With this set up this way, is it possible for me to run plain old UnitTests for my AuthRepository? Or is the dependency on Application going to force me to use Instrumentation Tests in order to test my AuthRepository?

Solution

1.You can mock Application class using Mockito:

@Mock private lateinit var context: Application

@Before fun setupTasksViewModel() {
    MockitoAnnotations.initMocks(this)
}
  1. or mock SharedPrefs object

    @Mock private lateinit var prefs: SharedPrefs
    

Answered By – Sergio

Answer Checked By – Willingham (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published