我不知道Powermock是否可以实现这一点。我需要使用Powermock来模拟在我需要测试的类的构造函数中调用的私有方法。所以我有一个这样的测试类:
@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());
}
}
}
创建间谍时,我得到一个空指针异常。构造函数new XMLTransaction(URL)调用initialize方法,这是我什么都不做的方法。
有没有办法解决这个问题。如果我使用默认构造函数,则不会创建该类。
我想出来了......我创建了一个默认构造函数,并将在initialize方法中实例化的所有类设置为null。从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");