38

I switched to Robolectric 4.0 Beta 1 from 3.8 because I need compatibility with Android 9 (API 28).

With this change, RuntimeEnvironment.application is now deprecated.

The replacement is apparently to use:

androidx.test.core.app.ApplicationProvider.getApplicationContext()

I have no idea where exactly this code is. It must be within a separate dependency entirely. Where is it? How do I add it to my project?

Thank you!

Charles Madere
  • 6,642
  • 5
  • 35
  • 34

1 Answers1

68

As described in the Robolectric Migration Guide to 4.0 you have to add the androidx test core dependencies testImplementation 'androidx.test:core:1.0.0' to your build.gradle After this you can use the ApplicationProvider.getApplicationContext() method

Nikki Borrelli
  • 899
  • 9
  • 21
dudi
  • 5,523
  • 4
  • 28
  • 57
  • 1
    But I am not able to access it in Local Unit Test Cases. I was using Robolectric library with RuntimeEnvironment.application. This says it's deprecated and the soultion is to use ApplicationProvider.getApplicationContext(). But how do I access it in as the libraries marked with androidTestImplementation are accessible in androidTests (Instrumentation Test Cases) only. Please guide. Reference - https://developer.android.com/training/testing/set-up-project#android-test-dependencies – Namrata Bagerwal Apr 15 '20 at 15:46
  • It's a bad practice to have a Context instance in Unit Test. Please mock the context in Unit Test if you need them there with Mockito or Mockk for Kotlin. Maybe you have to refactored your code so that you pass the context (or mock in the test) as parameter in your method. – dudi Apr 16 '20 at 13:10