Instancing the Application class in Unit Tests












0















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?










share|improve this question



























    0















    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?










    share|improve this question

























      0












      0








      0








      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?










      share|improve this question














      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?







      unit-testing kotlin retrofit android-testing






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 15 '18 at 17:28









      BlondeSwanBlondeSwan

      1319




      1319
























          1 Answer
          1






          active

          oldest

          votes


















          0














          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







          share|improve this answer
























          • Thanks! Since you have been able to answer a lot of my questions, would you mind if we started a private chat? Now that I have that, I need to figure out how to observe the response which requires an instance of LifeCycleOwner

            – BlondeSwan
            Nov 15 '18 at 17:48











          • sure, lets figure out that together

            – Sergey
            Nov 15 '18 at 17:54











          • Great, what's the best way to open a chat?

            – BlondeSwan
            Nov 15 '18 at 18:01











          • I thought you know :)

            – Sergey
            Nov 15 '18 at 18:10











          • I was going to contact you through your linked in profile, but it's not valid?

            – BlondeSwan
            Nov 15 '18 at 18:12











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53324936%2finstancing-the-application-class-in-unit-tests%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          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







          share|improve this answer
























          • Thanks! Since you have been able to answer a lot of my questions, would you mind if we started a private chat? Now that I have that, I need to figure out how to observe the response which requires an instance of LifeCycleOwner

            – BlondeSwan
            Nov 15 '18 at 17:48











          • sure, lets figure out that together

            – Sergey
            Nov 15 '18 at 17:54











          • Great, what's the best way to open a chat?

            – BlondeSwan
            Nov 15 '18 at 18:01











          • I thought you know :)

            – Sergey
            Nov 15 '18 at 18:10











          • I was going to contact you through your linked in profile, but it's not valid?

            – BlondeSwan
            Nov 15 '18 at 18:12
















          0














          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







          share|improve this answer
























          • Thanks! Since you have been able to answer a lot of my questions, would you mind if we started a private chat? Now that I have that, I need to figure out how to observe the response which requires an instance of LifeCycleOwner

            – BlondeSwan
            Nov 15 '18 at 17:48











          • sure, lets figure out that together

            – Sergey
            Nov 15 '18 at 17:54











          • Great, what's the best way to open a chat?

            – BlondeSwan
            Nov 15 '18 at 18:01











          • I thought you know :)

            – Sergey
            Nov 15 '18 at 18:10











          • I was going to contact you through your linked in profile, but it's not valid?

            – BlondeSwan
            Nov 15 '18 at 18:12














          0












          0








          0







          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







          share|improve this answer













          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








          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 15 '18 at 17:34









          SergeySergey

          4,21421835




          4,21421835













          • Thanks! Since you have been able to answer a lot of my questions, would you mind if we started a private chat? Now that I have that, I need to figure out how to observe the response which requires an instance of LifeCycleOwner

            – BlondeSwan
            Nov 15 '18 at 17:48











          • sure, lets figure out that together

            – Sergey
            Nov 15 '18 at 17:54











          • Great, what's the best way to open a chat?

            – BlondeSwan
            Nov 15 '18 at 18:01











          • I thought you know :)

            – Sergey
            Nov 15 '18 at 18:10











          • I was going to contact you through your linked in profile, but it's not valid?

            – BlondeSwan
            Nov 15 '18 at 18:12



















          • Thanks! Since you have been able to answer a lot of my questions, would you mind if we started a private chat? Now that I have that, I need to figure out how to observe the response which requires an instance of LifeCycleOwner

            – BlondeSwan
            Nov 15 '18 at 17:48











          • sure, lets figure out that together

            – Sergey
            Nov 15 '18 at 17:54











          • Great, what's the best way to open a chat?

            – BlondeSwan
            Nov 15 '18 at 18:01











          • I thought you know :)

            – Sergey
            Nov 15 '18 at 18:10











          • I was going to contact you through your linked in profile, but it's not valid?

            – BlondeSwan
            Nov 15 '18 at 18:12

















          Thanks! Since you have been able to answer a lot of my questions, would you mind if we started a private chat? Now that I have that, I need to figure out how to observe the response which requires an instance of LifeCycleOwner

          – BlondeSwan
          Nov 15 '18 at 17:48





          Thanks! Since you have been able to answer a lot of my questions, would you mind if we started a private chat? Now that I have that, I need to figure out how to observe the response which requires an instance of LifeCycleOwner

          – BlondeSwan
          Nov 15 '18 at 17:48













          sure, lets figure out that together

          – Sergey
          Nov 15 '18 at 17:54





          sure, lets figure out that together

          – Sergey
          Nov 15 '18 at 17:54













          Great, what's the best way to open a chat?

          – BlondeSwan
          Nov 15 '18 at 18:01





          Great, what's the best way to open a chat?

          – BlondeSwan
          Nov 15 '18 at 18:01













          I thought you know :)

          – Sergey
          Nov 15 '18 at 18:10





          I thought you know :)

          – Sergey
          Nov 15 '18 at 18:10













          I was going to contact you through your linked in profile, but it's not valid?

          – BlondeSwan
          Nov 15 '18 at 18:12





          I was going to contact you through your linked in profile, but it's not valid?

          – BlondeSwan
          Nov 15 '18 at 18:12




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53324936%2finstancing-the-application-class-in-unit-tests%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Florida Star v. B. J. F.

          Danny Elfman

          Lugert, Oklahoma