title: Mocking getClass method with PowerMockito
body: <p>I'd like to avoid mocking the getClass() method for a class but cannot seem to find any way around it. I'm trying to test a class that stores objects class types in a HashMap to a particular method to be used later. A brief example of this is:</p>
  
  <pre><code>public class ClassToTest {
      /** Map that will be populated with objects during constructor */
      private Map&lt;Class&lt;?&gt;, Method&gt; map = new HashMap&lt;Class&lt;?&gt;, Method&gt;();
  
      ClassToTest() {
          /* Loop through methods in ClassToTest and if they return a boolean and 
             take in an InterfaceA parameter then add them to map */
      }
  
      public void testMethod(InterfaceA obj) {
          final Method method = map.get(obj.getClass());
          boolean ok;
          if (method != null) {
               ok = (Boolean) method.invoke(this, obj);
          }
          if (ok) {
              obj.run();
          }
      }
  
      public boolean isSafeClassA(final ClassA obj) {
          // Work out if safe to run and then return true/false
      }
  
      public boolean isSafeClassB(final ClassB obj) {
         // Work out if safe to run and then return true/fals 
      }
  
  }
  
  public interface InterfaceA {
     void run()
  }
  
  public class ClassA implements InterfaceA {
     public void run() {
        // implements method here
     }
  }
  
  public class ClassB implements InterfaceA {
      public void run() {
         // implements method here
      }
  }
  </code></pre>
  
  <p>I then have a JUnit test that looks a little like this:</p>
  
  <pre><code>@RunWith(PowerMockRunner.class)
  @PrepareForTest({ClassA.class})
  public class ClassToTestTest {
      private final ClassToTest tester = new ClassToTest();
  
      @Test
      public void test() {
          MockGateway.MOCK_GET_CLASS_METHOD = true;
          final ClassA classA = spy(new ClassA());
          doReturn(ClassA.class).when(classA).getClass();
          MockGateway.MOCK_GET_CLASS_METHOD = false;
  
          tester.testMethod(classA);
          verify(classA).run();
      }
  }
  </code></pre>
  
  <p>My problem is although inside the test() method classA.getClass(); will return ClassA, once inside tester's testMethod() method it still returns the ClassA$EnhancerByMockitoWithCGLIB$... class and so my object useful will always be null.</p>
  
  <p>Is there any way I can get around mocking the class or what do I need to do to fix this?</p>
  
  <p>Thanks in advance.</p>