Search code examples
junitmockitopowermockito

how to mock an instance method invocation from static method while writing junit for static method?


how to mock an instance method invocation from static method while writing junit for static method?I'm writing tests for existing code.

class A
{
   public static D methodX()
   {
      B b = new B();
      C c = b.doSomething();
   }
}

class B
{
   public C doSomething()
   {
     return C;
   }
}

class Atest
{
    @Test
    public void testMethodX()
    {
       B b =Mockito.mock(B.class);
       Mockito.when(b.doSomething()).thenReturn(new C());
       A.methodX();
       // some assertions
    }
}

Solution

  • By your tag selection you already know that you need to go for PowerMockito.

    In order to inject a mocked version of B class i would do the following:

    A class

    class A
    {
       public static D methodX()
       {
          B b = getBInstance();
          C c = b.doSomething();
       }
    
       static B getBInstance(){
          return new B();
       }
    
    }
    

    Test Class

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(A.class)
    class Atest
    {
        @Test
        public void testMethodX()
        {
           B b =Mockito.mock(B.class);
           PowerMockito.stub(PowerMockito.method(A.class, "getBInstance")).toReturn(b);
           Mockito.when(b.doSomething()).thenReturn(new C());
           A.methodX();
           // some assertions
        }
    }
    

    Thanks to PowerMockito.stub(PowerMockito.method call you will just mock the getBInstance static method and in the end call the real A.methodX implementation.