[英]Using PowerMock to mock a private method called in the constructor of the class under test
I don't know if this is possible with Powermock. 我不知道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.
我需要使用Powermock来模拟在我需要测试的类的构造函数中调用的私有方法。 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.
构造函数new XMLTransaction(URL)调用initialize方法,这是我什么都不做的方法。
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. 我想出来了......我创建了一个默认构造函数,并将在initialize方法中实例化的所有类设置为null。 Removed this from initMock()
从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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.