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)
Share:
55,483

Related videos on Youtube

curiousMind
Author by

curiousMind

Updated on July 09, 2022

Comments

  • curiousMind
    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
    Brill Pappin about 5 years
    Can you add a little more answer to your answer?
  • Farruh Habibullaev
    Farruh Habibullaev almost 3 years
    It 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
    Daniele Ceglia over 2 years