1

I have an interface and its implementation which I can't change. Interface looks like this:

public Interface IHello{
// ... some method declarations
     public static class IoH{
          static IHello hello = new IHello.IoH.HelloImpl();
          public IoH(){}
          
          public static IHello getHello(){
              return hello;
          }

          private static class HelloImpl implements IHello{ 
              // .... constructor and methods....
          }
     }
}

I am also given an implementation of IHello interface, Hello (which is final class), which is just overriding the functions of IHello Interface and not doing anything else. That means it is not using any nested part of interface.

It is now used somewhere in the code as :

String string = IHello.IoH.getHello().getInfo(); // getInfo()  is method of interface

I'm unit testing and I want to mock this IHello.IoH.getHello() or IHello.IoH.getHello().getInfo() with either MockImplementation of IHello interface and injecting some bean or using Mockito...

How can I do this?

  • I guess it is nothing else than https://stackoverflow.com/questions/21105403 – Grim Jan 11 '21 at 10:19
  • Please who create interfaces like that should.... anyhow if you use Mockito 3.4.0 or later you can solve it with `MockedStatic` give it a try – Jocke Jan 12 '21 at 14:48
  • Thank you for your help! I went through the documentation and found this. Got it solved finally. – Tanmay Shivhare Jan 12 '21 at 15:40

1 Answers1

0

I have used Mockito version 3.4.0 and used MockedStatic

MockedStatic<IHello.IoH> mocked = Mockito.mockStatic(IHello.IoH.class);
mocked.when(IHello.IoH::getHello).thenReturn(new MockHello());

MockHello is simple implementation of your mocking idea, overriding functions of interface.