0

I have an Android App, which contains multiple java modules, means non-android modules. One module is core module which has no dependency on Android App module. But it takes Application Context at runtime.

I need to create a JUnit test case in this core module, that requires Android Application Context. I can do this by adding dependency of the Android Application module in core module in IntelliJ Idea by going to Project Settings.

But just for a JUnit test, I don't want to place dependency. Is there any way to mock this Application Context?

Please, let me know if anybody needs more clarification.

akhilesh0707
  • 6,709
  • 5
  • 44
  • 51
Anish Mittal
  • 1,157
  • 12
  • 29

1 Answers1

2

You can mock context like below using Mockito and use that :

private Context context;

context = Mockito.mock(Context.class);
Meenal
  • 2,879
  • 5
  • 19
  • 43
  • Yes, it works.+1 for that. But why can't we call getAssets() on this object. I referred https://stackoverflow.com/questions/32407178/mocking-android-assetmanager but no avail. – Anish Mittal Jul 26 '17 at 07:20
  • What about this one https://stackoverflow.com/questions/14970516/use-mockito-to-mock-some-methods-but-not-others – Eugen Pechanec Jul 26 '17 at 07:24
  • @Meenal : I get error. Cannot mock/spy class android.content.res.AssetManager Mockito cannot mock/spy following: - final classes - anonymous classes - primitive types – Anish Mittal Jul 26 '17 at 07:25
  • @Eugen: doesn't fulfill requirement – Anish Mittal Jul 26 '17 at 07:29
  • @AnishMittal I suggest you to use Robolectric for this, if it suits your requirement..as it provides Shadow Classes for all..so you don't have to mock.. – Meenal Jul 26 '17 at 07:33
  • @Meenal: I am using Android API 16 in IntelliJ Idea. Robolectric 1.2.jar & robolectric- 1.2-8-jar-with-dependencies.jar throwing "java.lang.NoClassDefFoundError: android/view/View". Even, I am not using any view. – Anish Mittal Jul 26 '17 at 08:50