title: Android Instrumented Test, Mock Final Classes
body: <p>How to mock final classes inside Android Instrumented Test cases, that is mocking  final classes inside <code>Android Run Time</code>?</p>
  
  <p>(I am using <code>Mockito 2.X</code>)</p>
  
  <p>I have a test case like follows -</p>
  
  <pre><code>import android.support.test.InstrumentationRegistry;
  import android.support.test.runner.AndroidJUnit4;
  import android.util.Log;
  import org.junit.Test;
  import org.junit.runner.RunWith;
  import static org.junit.Assert.*;
  
  import static org.mockito.Matchers.any;
  import static org.mockito.Mockito.mock;
  import static org.mockito.Mockito.verify;
  import static org.mockito.Mockito.when;
  
  @RunWith(AndroidJUnit4.class)
  public class ExampleInstrumentedTest {
  
      // This is my app specific NON - Final class
      private ShutdownServicesReqSig rebootSig = ShutdownServicesReqSig.newBuilder(ShutDownType.REBOOT_SYSTEM).setReason("test").build();
  
      private PowerManager mockedPowerManager = null;
  
      private Context mockedContext = null;
  
  
      @Test
      public void testRestart() throws InterruptedException
      {
  
          mockedContext = Mockito.mock(Context.class);
  
          mockedPowerManager = Mockito.mock(PowerManager.class);  // Here is the problem android.os.PowerManager is a Final class in latest Android SDK
                                                          // I need to mock it, only then I can use Mockito.verify() on PowerManager
  
          Mockito.when(mockedContext.getSystemService(Context.POWER_SERVICE)).thenReturn(mockedPowerManager);
  
          assertTrue(executor.requestShutdown(rebootSig));
  
          Thread.sleep(1000);
  
          Mockito.verify(mockedPowerManager).reboot(any(String.class)); // Mocking of PowerManager is essential to be sure of method call on PowerManager, using Mockito.verify 
  
          Mockito.reset(mockedPowerManager);
      }
  }
  </code></pre>
  
  <p>When I am running it as Android Instrumented Test on <code>ART</code>(placing inside - <code>MyApplication\app\src\androidTest</code>), I am getting following error - </p>
  
  <pre><code>org.mockito.exceptions.base.MockitoException:
  Cannot mock/spy class android.os.PowerManager
  Mockito cannot mock/spy following:
  - final classes
  - anonymous classes
  - primitive types
  </code></pre>
  
  <p>But, the same code, when I am running as a normal JUnit test, inside <code>JVM</code> (placing inside - <code>MyApplication\app\src\test</code>) it is working perfectly fine.</p>
  
  <p>I need to run it inside <code>ART</code>, as I like to test some of my customized Android Services, and I need to mock final classes like <code>PowerManager</code>, as only then I can use <code>Mockito.verify()</code> on <code>PowerManager</code>, to verify certain method calls on <code>PowerManager</code>.</p>
  
  <p>Help/guides are appreciated.</p>