【问题标题】:JUnit Test: Unable to unmarshall elementJUnit 测试:无法解组元素
【发布时间】:2019-11-04 06:53:56
【问题描述】:

我在网上尝试了无数解决方案后,近一周来遇到以下困难。具体问题与在我的 JUnit 测试中调用方法 Configuration.getUnmarshallerFactory().getUnmarshaller(Element) 后抛出 NullPointerException 有关。

以下是我的项目中导入opensaml库的依赖信息:

<dependency>
    <groupId>org.opensaml</groupId>
    <artifactId>opensaml</artifactId>
    <version>2.6.4</version>
</dependency>

以下是实现。在程序/项目正常执行期间,能够成功执行并返回Response对象。

private Response a(String text) throws ConfigurationException, SAXException  {

        DefaultBootstrap.bootstrap();

        Schema s = SAMLSchemaBuilder.getSAML11Schema();

        BasicParserPool bpp = new BasicParserPool();
        bpp.setNamespaceAware(true);
        bpp.setIgnoreElementContentWhitespace(true);
        bpp.setSchema(schema);

        InputStream is= new ByteArrayInputStream(Base64.decode(samlContent).getBytes());
        Response res= null;

        try {
            Document doc = bpp.parse(is);
            Element elmt= doc.getDocumentElement();
            try {

                QName qn = new QName(elmt.getNamespaceURI(), elmt.getLocalName(), elmt.getPrefix());
                Unmarshaller um = Configuration.getUnmarshallerFactory().getUnmarshaller(qn);        <== NullPointerException thrown at this line during JUnit Test**
                samlResponse = (Response) unmarshaller.unmarshall(elmt);
            } catch (XMLParserException e) {
                  logger.debug(e.getMessage());
        } catch (UnmarshallingException e) {
            logger.debug(e.getMessage());
        }

        return res;
    }

以下是JUnit测试: (我从以下网站获得了一个示例 samlp:Response 字符串:https://www.samltool.com/generic_sso_res.php

@Test
public void test() throws Exception {
    PowerMockito.mockStatic(DefaultBootstrap.class);       
    PowerMockito.doNothing().when(DefaultBootstrap.class, "bootstrap");


    Response result = classInstance.a(Base64.encode(responseStringFromWebsite));

    assertNotNull(result);
}

如果你们之前遇到过类似的错误,我将非常感谢任何帮助或知识分享。

【问题讨论】:

    标签: java mockito junit5 powermockito opensaml


    【解决方案1】:

    通过模拟 DefaultBootstrap # bootstrap 方法,我猜你已经跳过了必填字段的初始化。查看 DefaultBootstrap.bootstrap() 的源代码,它会阐明 NPE 的原因。

    【讨论】:

    • 您有什么建议可以帮助在 JUnit 中通过以下行 DefaultBootstrap.bootstrap() 而不使用以下模拟方法?
    • Field xmlToolingConfigs = Whitebox.getField(DefaultBootstrap.class, "xmlToolingConfigs"); Whitebox.invokeMethod(DefaultBootstrap.class, "initializeXMLTooling", xmlToolingConfigs.get(DefaultBootstrap.class)); 此代码将初始化您的解组器,您的测试必须通过(希望如此)。你确定,你需要模拟 DefaultBootstrap.bootstrap()?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 2016-07-14
    相关资源
    最近更新 更多