Question

I have the following legacy singleton class that I'm trying to test :

public class Controller {
   private handler = HandlerMgr.getHandler();
   public static final instance = new Controller();

   private Controller() {

   }

  public int process() {
     List<Request> reqs = handler.getHandler();
     ....
  }
}

I have tried the following, but to no avail :

  @Test
  public void test() {
    mockStatic(HandlerMgr.class);
    when(Handler.getHandler()).theReturn(expectedRequests);
    int actual = Controller.instance.process();
    // ... assertions ...
  }

the issue is that HandlerMgr.getHandler() still gets called, I want to bypass it and mock it out.

Was it helpful?

Solution

As per my comment

Your Controller calls the getHandler but set the expectation on the GetRequest ? This is probably why the real method get called?

And then referring to the documentation it seems that you are missing an expectation on the stub you have generated by mockStatic.

As per the PowerMock documentation ... Please see below.

@Test
public void testRegisterService() throws Exception {
    long expectedId = 42;

    // We create a new instance of test class under test as usually.
    ServiceRegistartor tested = new ServiceRegistartor();

    // This is the way to tell PowerMock to mock all static methods of a
    // given class
    mockStatic(IdGenerator.class);

    /*
     * The static method call to IdGenerator.generateNewId() expectation.
     * This is why we need PowerMock.
     */
    expect(IdGenerator.generateNewId()).andReturn(expectedId);

    // Note how we replay the class, not the instance!
    replay(IdGenerator.class);

    long actualId = tested.registerService(new Object());

    // Note how we verify the class, not the instance!
    verify(IdGenerator.class);

    // Assert that the ID is correct
    assertEquals(expectedId, actualId);
}

https://code.google.com/p/powermock/wiki/MockStatic

Since your expectation / setup is missing grtHandler, the real method still get called.

OTHER TIPS

Add @PrepareForTest({HandlerMgr.class}) to the test class .you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top