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?