Reputation: 187
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
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:
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