I'm using Context to access system level services like WifiManager and BluetoothManager. How to mock this getApplicationContext() using Mockito?
Asked
Active
Viewed 7.0k times
4 Answers
41
Context context = mock(Context.class);

Sipty
- 1,159
- 1
- 10
- 18
-
1It looks like it's not working in newer version of Mockito. Mockito forbids mocking types which have complex contracts or easy to construct by other means. It throws the exception `'context' is mocking 'class android.content.Context'. Don't mock android components, as they have lots of state and complex behavior - use the real thing. A Context can be obtained from ApplicationProvider.getApplicationContext() in Robolectric tests, or from InstrumentationRegistry in emulator tests..` – Farruh Habibullaev Jul 02 '21 at 04:36
26
If you want to get the context with Kotlin
and Mockito
, you can do it in the following way:
mock(Context::class.java)

Juanes30
- 2,398
- 2
- 24
- 38
9
Let's have a look at the following class: MockContext
If you need more insight, check the Official Testing Fundamentals page
0
Don't mock types you don't own. But why? let's say you are mocking a third-party library, if the maintainers of that library made changes, then your tests will be executed because it is a mock and you think everything is okay, but it is not because there are changes that you are not aware of, and things can go badly.

Younes Belouche
- 1,183
- 6
- 7