I have a REST endpoint that generates random images. I'm using Spring REST Docs, but the Response is all garbled in the http-response.adoc file. Is there an easy way for Mock MVC and REST Docs to store the file somewhere so my .adoc files can reference it?
Not the perfect but working solution:
class ImageSnippet implements Snippet {
private final String filePath;
public ImageSnippet(String filePath) {
this.filePath = filePath;
}
@Override
public void document(Operation operation) throws IOException {
byte[] picture = operation.getResponse().getContent();
Path path = Paths.get(filePath);
Files.deleteIfExists(path);
Files.createDirectories(path.getParent());
Files.createFile(path);
try (FileOutputStream fos = new FileOutputStream(path.toFile())) {
fos.write(picture);
}
}
}
And usage in MockMvc test (image folder path is important):
mockMvc.perform(get("/my-profile/barcode")
.accept(MediaType.IMAGE_PNG))
.andExpect(status().isOk())
.andDo(document("my-profile/barcode",
new ImageSnippet("build/asciidoc/html5/images/barcode.png")));
In .adoc
template:
image::barcode.png[]
And here is my build.gradle
Asciidoctor configuration (imagesdir
is important):
asciidoctor {
dependsOn test
backends = ['html5']
options doctype: 'book'
attributes = [
'source-highlighter': 'highlightjs',
'imagesdir' : './images',
'toc' : 'left',
'toclevels' : 3,
'numbered' : '',
'icons' : 'font',
'setanchors' : '',
'idprefix' : '',
'idseparator' : '-',
'docinfo1' : '',
'safe-mode-unsafe' : '',
'allow-uri-read' : '',
'snippets' : snippetsDir,
linkattrs : true,
encoding : 'utf-8'
]
inputs.dir snippetsDir
outputDir 'build/asciidoc'
sourceDir 'src/docs/asciidoc'
sources {
include 'index.adoc'
}
}