其余文档使用自定义 Snippet 类被忽略

问题描述

我想包含我的自定义 Snippet 类,因此我遵循了 docs(我使用 junit 5)。

@BeforeEach()
    public void test(WebApplicationContext webApplicationContext,RestDocumentationContextProvider restDocumentationContextProvider){
        mockmvc = mockmvcBuilders.webAppContextSetup(webApplicationContext)
                .apply(documentationConfiguration(restDocumentationContextProvider).snippets()
                        .withDefaults(curlRequest())).build();
    }

这个测试失败了,因为我所有的 Mocks ( Mockito ) 在测试期间都是空的。

总的来说,我想使用我的自定义实现:

public class CustomHttpRequest extends HttpRequestSnippet {


    public CustomHttpRequest(Map<String,Object> attributes) {
        super(attributes);
    }

    @Override
    protected Map<String,Object> createModel(Operation operation) {
        Map<String,Object> model = super.createModel(operation);
        model.put("custom-path",removeQueryStringIfPresent(extractUrlTemplate(operation)));
        return model;
    }

    private String removeQueryStringIfPresent(String urlTemplate) {
        int index = urlTemplate.indexOf('?');
        if (index == -1) {
            return urlTemplate;
        }
        return urlTemplate.substring(0,index);
    }

    private String extractUrlTemplate(Operation operation) {
        String urlTemplate = (String) operation.getAttributes()
                .get(RestDocumentationGenerator.ATTRIBUTE_NAME_URL_TEMPLATE);
        Assert.notNull(urlTemplate,"urlTemplate not found. If you are using mockmvc did "
                + "you use RestDocumentationRequestBuilders to build the request?");
        return urlTemplate;
    }
}

我适应了:

 @BeforeEach()
    public void test(WebApplicationContext webApplicationContext,RestDocumentationContextProvider restDocumentationContextProvider){
        mockmvc = mockmvcBuilders.webAppContextSetup(webApplicationContext)
                .apply(documentationConfiguration(restDocumentationContextProvider).snippets()
                        .withAdditionalDefaults(new CustomHttpRequest(null))).build();
    }

但仍然是我所有的 Mockito 当...然后...定义导致 Nullpointer 异常。

例如

 @MockBean
    private AccountService accountService;

when(accountService.getAccountById(anyString())).thenReturn(account);

将我的自定义类包含到其他现有代码段的正确方法是什么? 我是否还必须提供将要创建的 .snippet 文件? 为什么文档中的片段会导致此错误

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)