4

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
    }
}
AVVD
  • 78
  • 1
  • 10

2 Answers2

1

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.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
1

Another completely different approach: do not write un-testable code. static is an abnormality within good OO designs; to the first step is to simply not write static methods.

And when you have good reasons to still do so; then write them in a way that allows you reasonable unit-test them.

Yes, it is possible to turn to PowerMock(ito) to get this solved, but the more sane approach is to simple fix your production design.

The PowerMock(ito) frameworks come at certain cost; and can easily be avoided.

Thus, my answer: learn how to create testable code; and simply forget about PowerMock (you can start by watching these videos).

GhostCat
  • 137,827
  • 25
  • 176
  • 248