I don't know if this is possible with Powermock. I need to use Powermock to mock a private method that is called in the constructor of the class that I need to test. So I have a test class like this:
@RunWith(PowerMockRunner.class)
@PrepareForTest(XMLTransaction.class)
public class CloseSummaryOrCloseTrailerResponseTest {
public final static String URL="WL_APPSERVER";
private XMLTransaction xmlTransaction;
@Before
public void initMocks() throws Exception {
xmlTransaction = PowerMockito.spy(new XMLTransaction(URL));
PowerMockito.doAnswer(new org.mockito.stubbing.Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return null; //does nothing
}
}).when(xmlTransaction.getClass(), "initialize");
PowerMockito.doNothing().when(xmlTransaction.getClass(), "initialize");
}
@Test
public void whenCloseSummaryResponseNoErrorExpectCorrectXmlMsgProduced () throws Exception
{
//set the mock object here
try {
String actualXmlScannerMsg = xmlTransaction.closeSummaryResponseToXMLNoErrors(mockCloseTrailerResponse);
Assert.assertNotNull(actualXmlScannerMsg);
Assert.assertEquals(msgNoCarReturnCharCloseSummaryResponse, actualXmlScannerMsg);
}
catch(JsonProcessingException jEx)
{
Assert.fail("JsonProcessingException: " + jEx.getMessage());
}
catch(Exception ex)
{
Assert.fail("Exception occurred: " + ex.getMessage());
}
}
}
I get a null pointer exception when creating the spy. The constructor new XMLTransaction(URL) calls the initialize method which is the method I want to do nothing.
Is there any way to get around this problem. If I use the default constructor, the class is not created.
I figured this out... I created a default constructor and set all of the classes instantiated in the initialize method to null. Removed this from initMock()
PowerMockito.doAnswer(new org.mockito.stubbing.Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return null; //does nothing
}
}).when(xmlTransaction.getClass(), "initialize");
PowerMockito.doNothing().when(xmlTransaction.getClass(), "initialize");