【问题标题】:Using PowerMock to mock a private method called in the constructor of the class under test使用 PowerMock 模拟在被测类的构造函数中调用的私有方法
【发布时间】:2019-03-20 02:25:15
【问题描述】:

我不知道这是否可以通过 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 方法,这是我什么都不想做的方法。

有什么办法可以解决这个问题。如果我使用默认构造函数,则不会创建该类。

【问题讨论】:

    标签: java junit4 powermockito


    【解决方案1】:

    我想通了... 我创建了一个默认构造函数,并将在 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");  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 2016-12-28
      • 2014-08-17
      • 2016-05-28
      相关资源
      最近更新 更多