10

I'm trying to write a unit test which uses mock JSON responses.

Basically, my intent was to add the json files to /res/raw, and access them using the same method I would within the application:

InputStream jsonStream = context.getResources().openRawResource(R.raw.mock_json_response)

But when I do this I get the following error:

android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f060001

I'm using robolectric for testing - I'm not sure if that changes the way in which external files would have to be accessed.

I've tried putting the JSON file in both /app/src/main/res and /app/src/test/res but neither seems to work.

Is it possible to access resources in a test in this way?

sak
  • 2,612
  • 24
  • 55
  • Did you read though this post ? http://stackoverflow.com/questions/9249751/accessing-resources-in-an-android-test-project – Nik Myers May 07 '15 at 14:23
  • Looks like duplication, see similar question at http://stackoverflow.com/questions/30063483/robolectric-throws-resourcesnotfoundexception-when-trying-to-access-resource-in – nenick May 07 '15 at 16:23
  • In order to access android resources you nedd a **Context** . where is your context ? – Omar Beshary Nov 09 '18 at 21:54

1 Answers1

0

No, you cannot use resource ids during unit tests. Unit tests mean what they will be run without real device and any relation to real resources (During unit tests you doesn't have access to context so you doesn't have access to resources).

As a workaround:

  1. You can mock your interactor/use case and use your json as string.
  2. You can use UI tests with Espresso and PowerMock.

PowerMock allow you to mock web responses with json files.

Hope it'll help.

Peter Staranchuk
  • 1,343
  • 3
  • 14
  • 29