Search code examples
javaunit-testinganttestngpowermockito

Power Mockito fails to mock constructor


In order to test some legacy code, I have to use Power Mockito. Reason is that the legacy code is not using dependency injection and due to some reasons, we can't refactor the code at this time. We are running testng with ANT in our system. I have configured build.xml to use power mock and power mock testng libraries. I want to mock a constructor using Power Mockito and below is the sample code.

public class Something {
     private String arg = null;

     public Something() {

     }

     public Something(String _arg) {
        arg = _arg;
     }

     public String doSomething() {
         return arg;
     }
 }

public class Helper {
     public Something doSomething(String arg) {
         return new Something();
     }
}

@PrepareEverythingForTest
class TestSC {
     @Test
     public void testHelper() throws Exception {
         Something mockSomething = PowerMockito.mock(Something.class);
         PowerMockito.whenNew(Something.class).withNoArguments().thenReturn(mockSomething);

         Helper helper = new Helper();
         Something test = helper.doSomething("arg");
         Assert.assertEquals(test, mockSomething);
     }
}

This test fails and I have no clue what is going on wrong here. Also I have seen below link to configure testng with power mockito. https://github.com/jayway/powermock/wiki/TestNG_usage

I tried extending my test class to PowerMockTestCase and it gaves me below error while running test.

   [testng] [TestNG] [ERROR]
   **[testng] Error creating object factory**
   [testng] The tests failed.

I have below doubts in mind:-

1) Either my testng is not configured properly to use Power Mockito, but power mockito simple testcase works.

2) Some configuration is missing.


Solution

  • I figure out the issue lately, it was because of some dependency library i.e.javassist which was quite old. Replacing it with the newer version 3.20 resolved the issue and PowerMockito constructor mocking worked.