mongo插入的nullpointerexception

问题描述 投票:1回答:1

我有以下代码,应该将文档插入到MongoDB集合中,如下所示(注意,我在类上方有@ Slf4j批注,应该让我使用日志):

    public Document functionName(Document document) {

        return reactiveMongoTemplate.insert(document)
                .doOnSuccess(param -> log.info("Successfully saved"))
                .onErrorResume(e -> {
                    String message = format("Error saving %s", e.getMessage());
                    log.error(message, e);
                    throw new Exception(message, e);
                })
                .block();
    }

当我为此做一个单元测试用例并测试了功能时,当我真的希望测试能够通过时,在doOnSuccess的行上我得到了一个空指针异常。我在这里缺少对reactMongoTemplate特定的东西吗?

这里是单元测试:

    @Test
    void successfulMongoInsertion() {
        String xmlString = "<header>\n" +
                "    <to>Me</to>\n" +
                "    <from>You</from>\n" +
                "</header>";

        JSONObject json = XML.toJSONObject(xmlString);
        Document xmlDocument = Document.parse(json.toString());

        service.functionName(xmlDocument);
        ArgumentCaptor<Document> captor = ArgumentCaptor.forClass(Document.class);
        verify(reactiveMongoTemplate).insert(captor.capture());

        Document retrievedDocument = captor.getValue();
        assertTrue(xmlDocument.equals(retrievedDocument));
    }

服务是具有我之前包含的functionName方法的对象。

java mongodb reactivemongo
1个回答
0
投票
您的单元测试方法不会从您的主类实例化日志。您可以通过构造函数或Java Bean使其可分配,并在测试之前通过新的记录器。
© www.soinside.com 2019 - 2024. All rights reserved.