How to mock Context using Mockito?
55,483
Solution 1
Let's have a look at the following class: MockContext
If you need more insight, check the Official Testing Fundamentals page
Solution 2
Context context = mock(Context.class);
Solution 3
If you want to get the context with Kotlin
and Mockito
, you can do it in the following way:
mock(Context::class.java)
Related videos on Youtube
![curiousMind](https://i.stack.imgur.com/VKWL5.jpg?s=256&g=1)
Author by
curiousMind
Updated on July 09, 2022Comments
-
curiousMind almost 2 years
I'm using Context to access system level services like WifiManager and BluetoothManager. How to mock this getApplicationContext() using Mockito?
-
Brill Pappin about 5 yearsCan you add a little more answer to your answer?
-
Farruh Habibullaev almost 3 yearsIt 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..
-
Daniele Ceglia over 2 yearsMore info: stackoverflow.com/a/57296849/2425030