mercredi 2 mars 2016

Mock string resource in Android unit testing using Robolectric 3

I've read a couple of answers online but none of them seem to work for me.

This is what I have in my @Setup method:

MockitoAnnotations.initMocks(this);
Configuration mConfiguration = Mockito.mock(Configuration.class);
mConfiguration.locale = Locale.US;
when(mContext.getResources().getConfiguration()).thenReturn(mConfiguration);
when(StorageUtils.getUserAgent(mContext)).thenReturn("User-Agent: Android Unit Test");
when(mContext.getResources().getString(R.string.service_domain)).thenReturn("testString");

All of it works, except the last line getString. Ideally the string would be from the actual strings resource I already have for the whole app, but if that's not possible, I can add it to this line manually.

The part that doesn't work is when I try to call the string.

The .getString(R.string.service_domain) part is getting called in another method (the method used in the actual application) as part of the context.

So my method is called like this from unit test:

Utils.getProductImageUrl(mContext, product);

And this getProductImageUrl does this:

productImageUrl = context.getString(R.string.service_domain) + baseImageUrl;

When I run the unit test, the productImageUrl variable get a full url of

null/123.png

How can I mock the string so it can be passed as part of the context to my method?

Let me know if you need additional information. Thank you.

Aucun commentaire:

Enregistrer un commentaire