I want to include a custom Snippet class of mine and therefor I followed the docs ( I use junit 5 ).
@BeforeEach()
public void test(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentationContextProvider){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(restDocumentationContextProvider).snippets()
.withDefaults(curlRequest())).build();
}
This test fails as all my Mocks ( Mockito ) are null during the test.
In general I wanted to use my custom implementation:
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;
}
}
and I adapted to:
@BeforeEach()
public void test(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentationContextProvider){
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(restDocumentationContextProvider).snippets()
.withAdditionalDefaults(new CustomHttpRequest(null))).build();
}
But still all my Mockito when... then.. definition are causing a Nullpointer exception.
e.g.
@MockBean
private AccountService accountService;
when(accountService.getAccountById(anyString())).thenReturn(account);
What is the correct way to include my custom class to the other existing snippets? Do I have to provide a .snippet file also that is will be created? And why does the snippet from the docs cause this error?