Tapan
Tapan

Reputation: 187

Power Mockito WhenNew does'nt work

So I have a class to be tested which has a Constructor -

public class IdRunnable{
    public IdRunnable(Node root) {
            this.saHandler = new Handler(root);
    }

    public void call(){
    //Somes codes 
    }
}

I am using Powermock framework to inject the mock object when the new operator is called. The testing class is-

@RunWith(PowerMockRunner.class)
@PrepareForTest({IdRunnable.class,Handler.class})
public class IdRunnableTest { 
    private IdRunnable runnable;

    @BeforeClass
    public void oneTimeSetUp(){
        Node root = new Node();
        Handler handler = mock(Handler.class);
        whenNew(Handler.class).withArguments(root).thenReturn(handler);
        runnable = new IdRunnable(root);
    }

    @Test(groups = {TestGroup.UNIT_TESTS})
    public void testCall(){
        runnable.call();
    }
}

When I run the test I can see that instead of mocking the new statement in IdRunnable's constructor It goes on create the real Handler Object. Somehow the code-

whenNew(Handler.class).withArguments(root).thenReturn(handler);

does not work for me. Can anyone suggest what is wrong with the code.

Thanks.

Upvotes: 2

Views: 2506

Answers (1)

GhostCat
GhostCat

Reputation: 140427

Of course that is possible; but such a waste of energy.

Just do:

public IdRunnable(Node root) {
   this(new Handler(root);
}

IdRunnable(Handler saHandler) {
   this.saHandler = saHandler;
}

and your "need" to turn to PowerMock just vanishes. And yes, not needing PowerMock is a good thing. Because now you can use a constructor that allows you injecting that object that you need to mock.

Because it means that you prefer to write testable code. In my experience:

  1. Powermock sometimes offers ugly surprises (such as test cases failing all of a sudden with obscure problems; not at all rooted in production code bugs)
  2. It can be easily avoided, by learning how to create testable code.

Edit: given your comment; your only choice is to get PowerMock(ito) working for you. Probably this answer of mine helps. It contains a small example for mocking constructor calls; shouldn't be a big deal to adapt it to your needs.

Upvotes: 1

Related Questions