Mocking default SharedPreferences












2















So I have a class that takes in a Context through the constructor, and grabs the default SharedPreferences from it using:



PreferenceManager.getDefaultSharedPreferences(context)


I'm testing this class, and in my unit test I've written the following code to retrieve a mocked SharedPreferences instance when getSharedPreferences(String, int) is invoked:



Context context = mock(Context.class);
SharedPreferences sharedPreferences = mock(SharedPreferences.class);

when(context.getSharedPreferences(anyString(), anyInt()))
.thenReturn(sharedPreferences);
when(sharedPreferences.getString(anyString(), nullable(String.class)))
.thenReturn(tokenManager.getToken());


When I run the test for this class, it ends up with a null object instead of my mocked SharedPreferences instance. However, if I grab the SharedPreferences instance with context.getSharedPreferences("stubbed", 123), I end up with my mocked SharedPreferences code.



So why does PreferenceManager.getDefaultSharedPreferences(context) return null instance while directly calling getSharedPreferences on my mock Context returns my mocked SharedPreferences instance?










share|improve this question























  • did you check the code of PreferenceManager.getDefaultSharedPreferences(context)? How does the PM get the data from the context?

    – P.J.Meisch
    Nov 17 '18 at 16:54













  • `return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());``

    – Jonathan Chiou
    Nov 19 '18 at 17:03
















2















So I have a class that takes in a Context through the constructor, and grabs the default SharedPreferences from it using:



PreferenceManager.getDefaultSharedPreferences(context)


I'm testing this class, and in my unit test I've written the following code to retrieve a mocked SharedPreferences instance when getSharedPreferences(String, int) is invoked:



Context context = mock(Context.class);
SharedPreferences sharedPreferences = mock(SharedPreferences.class);

when(context.getSharedPreferences(anyString(), anyInt()))
.thenReturn(sharedPreferences);
when(sharedPreferences.getString(anyString(), nullable(String.class)))
.thenReturn(tokenManager.getToken());


When I run the test for this class, it ends up with a null object instead of my mocked SharedPreferences instance. However, if I grab the SharedPreferences instance with context.getSharedPreferences("stubbed", 123), I end up with my mocked SharedPreferences code.



So why does PreferenceManager.getDefaultSharedPreferences(context) return null instance while directly calling getSharedPreferences on my mock Context returns my mocked SharedPreferences instance?










share|improve this question























  • did you check the code of PreferenceManager.getDefaultSharedPreferences(context)? How does the PM get the data from the context?

    – P.J.Meisch
    Nov 17 '18 at 16:54













  • `return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());``

    – Jonathan Chiou
    Nov 19 '18 at 17:03














2












2








2








So I have a class that takes in a Context through the constructor, and grabs the default SharedPreferences from it using:



PreferenceManager.getDefaultSharedPreferences(context)


I'm testing this class, and in my unit test I've written the following code to retrieve a mocked SharedPreferences instance when getSharedPreferences(String, int) is invoked:



Context context = mock(Context.class);
SharedPreferences sharedPreferences = mock(SharedPreferences.class);

when(context.getSharedPreferences(anyString(), anyInt()))
.thenReturn(sharedPreferences);
when(sharedPreferences.getString(anyString(), nullable(String.class)))
.thenReturn(tokenManager.getToken());


When I run the test for this class, it ends up with a null object instead of my mocked SharedPreferences instance. However, if I grab the SharedPreferences instance with context.getSharedPreferences("stubbed", 123), I end up with my mocked SharedPreferences code.



So why does PreferenceManager.getDefaultSharedPreferences(context) return null instance while directly calling getSharedPreferences on my mock Context returns my mocked SharedPreferences instance?










share|improve this question














So I have a class that takes in a Context through the constructor, and grabs the default SharedPreferences from it using:



PreferenceManager.getDefaultSharedPreferences(context)


I'm testing this class, and in my unit test I've written the following code to retrieve a mocked SharedPreferences instance when getSharedPreferences(String, int) is invoked:



Context context = mock(Context.class);
SharedPreferences sharedPreferences = mock(SharedPreferences.class);

when(context.getSharedPreferences(anyString(), anyInt()))
.thenReturn(sharedPreferences);
when(sharedPreferences.getString(anyString(), nullable(String.class)))
.thenReturn(tokenManager.getToken());


When I run the test for this class, it ends up with a null object instead of my mocked SharedPreferences instance. However, if I grab the SharedPreferences instance with context.getSharedPreferences("stubbed", 123), I end up with my mocked SharedPreferences code.



So why does PreferenceManager.getDefaultSharedPreferences(context) return null instance while directly calling getSharedPreferences on my mock Context returns my mocked SharedPreferences instance?







java android mockito sharedpreferences






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 16 '18 at 23:14









Jonathan ChiouJonathan Chiou

119213




119213













  • did you check the code of PreferenceManager.getDefaultSharedPreferences(context)? How does the PM get the data from the context?

    – P.J.Meisch
    Nov 17 '18 at 16:54













  • `return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());``

    – Jonathan Chiou
    Nov 19 '18 at 17:03



















  • did you check the code of PreferenceManager.getDefaultSharedPreferences(context)? How does the PM get the data from the context?

    – P.J.Meisch
    Nov 17 '18 at 16:54













  • `return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());``

    – Jonathan Chiou
    Nov 19 '18 at 17:03

















did you check the code of PreferenceManager.getDefaultSharedPreferences(context)? How does the PM get the data from the context?

– P.J.Meisch
Nov 17 '18 at 16:54







did you check the code of PreferenceManager.getDefaultSharedPreferences(context)? How does the PM get the data from the context?

– P.J.Meisch
Nov 17 '18 at 16:54















`return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());``

– Jonathan Chiou
Nov 19 '18 at 17:03





`return context.getSharedPreferences(getDefaultSharedPreferencesName(context), getDefaultSharedPreferencesMode());``

– Jonathan Chiou
Nov 19 '18 at 17:03












2 Answers
2






active

oldest

votes


















0














Based on this document (https://developer.android.com/training/testing/unit-testing/local-unit-tests) and debugging the code line by line, the conclusion I've reached about why this occurs is because the android code used for unit tests in gradle is actually just a shell that returns stubbed values on every method invocation, so naturally that leads me to assume that the code for PreferenceManager.getDefaultSharedPreferences() that's being used in my unit tests is more or less return null.






share|improve this answer































    0














    So you need to mock the static call to PreferenceManager.getDefaultSharedPreferences(context). This is not possible at the moment with mockito, there is still discussion going on the corresponding issue.



    One solution is shown in the accepted answer of this question, you could check PowerMock or JMockit as alternatives






    share|improve this answer























      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%2f53346583%2fmocking-default-sharedpreferences%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      Based on this document (https://developer.android.com/training/testing/unit-testing/local-unit-tests) and debugging the code line by line, the conclusion I've reached about why this occurs is because the android code used for unit tests in gradle is actually just a shell that returns stubbed values on every method invocation, so naturally that leads me to assume that the code for PreferenceManager.getDefaultSharedPreferences() that's being used in my unit tests is more or less return null.






      share|improve this answer




























        0














        Based on this document (https://developer.android.com/training/testing/unit-testing/local-unit-tests) and debugging the code line by line, the conclusion I've reached about why this occurs is because the android code used for unit tests in gradle is actually just a shell that returns stubbed values on every method invocation, so naturally that leads me to assume that the code for PreferenceManager.getDefaultSharedPreferences() that's being used in my unit tests is more or less return null.






        share|improve this answer


























          0












          0








          0







          Based on this document (https://developer.android.com/training/testing/unit-testing/local-unit-tests) and debugging the code line by line, the conclusion I've reached about why this occurs is because the android code used for unit tests in gradle is actually just a shell that returns stubbed values on every method invocation, so naturally that leads me to assume that the code for PreferenceManager.getDefaultSharedPreferences() that's being used in my unit tests is more or less return null.






          share|improve this answer













          Based on this document (https://developer.android.com/training/testing/unit-testing/local-unit-tests) and debugging the code line by line, the conclusion I've reached about why this occurs is because the android code used for unit tests in gradle is actually just a shell that returns stubbed values on every method invocation, so naturally that leads me to assume that the code for PreferenceManager.getDefaultSharedPreferences() that's being used in my unit tests is more or less return null.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 '18 at 21:47









          Jonathan ChiouJonathan Chiou

          119213




          119213

























              0














              So you need to mock the static call to PreferenceManager.getDefaultSharedPreferences(context). This is not possible at the moment with mockito, there is still discussion going on the corresponding issue.



              One solution is shown in the accepted answer of this question, you could check PowerMock or JMockit as alternatives






              share|improve this answer




























                0














                So you need to mock the static call to PreferenceManager.getDefaultSharedPreferences(context). This is not possible at the moment with mockito, there is still discussion going on the corresponding issue.



                One solution is shown in the accepted answer of this question, you could check PowerMock or JMockit as alternatives






                share|improve this answer


























                  0












                  0








                  0







                  So you need to mock the static call to PreferenceManager.getDefaultSharedPreferences(context). This is not possible at the moment with mockito, there is still discussion going on the corresponding issue.



                  One solution is shown in the accepted answer of this question, you could check PowerMock or JMockit as alternatives






                  share|improve this answer













                  So you need to mock the static call to PreferenceManager.getDefaultSharedPreferences(context). This is not possible at the moment with mockito, there is still discussion going on the corresponding issue.



                  One solution is shown in the accepted answer of this question, you could check PowerMock or JMockit as alternatives







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 20 '18 at 7:46









                  P.J.MeischP.J.Meisch

                  5,21642142




                  5,21642142






























                      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%2f53346583%2fmocking-default-sharedpreferences%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

                      How to send String Array data to Server using php in android

                      Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                      Is anime1.com a legal site for watching anime?