Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assets folder in Android Studio Unit Test

People also ask

Where is assets Folder in Android Studio?

In a typical Android Studio project, you will have an app/ module, with a main/ sourceset ( app/src/main/ off of the project root), and so your primary assets would go in app/src/main/assets/ .

What is the use of assets Folder in Android?

Assets provide a way to include arbitrary files like text, xml, fonts, music, and video in your application. If you try to include these files as "resources", Android will process them into its resource system and you will not be able to get the raw data.

How do I find the assets Folder?

Step 1: To create an asset folder in Android studio open your project in Android mode first as shown in the below image. Step 2: Go to the app > right-click > New > Folder > Asset Folder and create the asset folder.

How do I access Android assets?

Step 3 – Right click app >> New >> Folder >> Assets folder. Right click on the assets folder, select New >> file (myText. txt) and your text.


It looks like you're trying to create an instrumented unit test, since you want to create it in the androidTest folder.

You can use one of these two lines in your test to get the context:

  • Context ctx = InstrumentationRegistry.getTargetContext(); this one will give you your app's context. You can use it to grab assets that are in src/main/assets for example.

  • Context ctx = InstrumentationRegistry.getContext(); this one will give you the test app's context. You can use it to grab assets that are in src/androidTest/assets

If you want to know more about assets in unit testing you can read this post. In this github file you have an example.

Deprecation Note: As pointed out in the comments, these methods are now deprecated. This is the new recommended way:

  • First, instead of importing the old InstrumentationRegistry class, use the new one.
  • Instead of InstrumentationRegistry.getTargetContext(); use ApplicationProvider.getApplicationContext(). Source
  • For InstrumentationRegistry.getTargetContext();: In most scenarios, ApplicationProvider.getApplicationContext() should be used instead of the instrumentation test context. If you do need access to the test context for to access its resources, it is recommended to use PackageManager.getResourcesForApplication(String) instead. Source

I think you use the wrong context ( the application-context and not the instrumentation context ) use:

getInstrumentation().getContext();

Or see here where I exactly do what you want to do: https://github.com/ligi/gobandroid/blob/master/android/src/androidTest/java/org/ligi/gobandroidhd/base/AssetAwareInstrumentationTestCase.java