Skip to content

Instantly share code, notes, and snippets.

@wkorando
Last active August 19, 2018 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wkorando/8696365dc274608a0554f8bde9d6c35c to your computer and use it in GitHub Desktop.
Save wkorando/8696365dc274608a0554f8bde9d6c35c to your computer and use it in GitHub Desktop.
public class TestAcceptedMediaTypes {
private static final MediaType[] SUPPORTED_MEDIA_TYPES = new MediaType[] { MediaType.APPLICATION_JSON_UTF8,
MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML };
@TestFactory
Collection<DynamicContainer> testAcceptedMediaTypes() throws Exception {
...
List<DynamicContainer> dynamicContainers = new ArrayList<>();
// Check if controller has a POST endpoint and call it with all the different
// mediatypes, throw an error in a 415 (unsupported media type) is returned
for (Class<?> controllerClazz : controllersClasses) {
RequestMapping mapping = controllerClazz.getAnnotationsByType(RequestMapping.class)[0];
StringBuilder builder = new StringBuilder();
builder.append(mapping.value()[0]);
for (Method method : controllerClazz.getMethods()) {
if (method.isAnnotationPresent(PostMapping.class)) {
List<DynamicTest> dynamicTests = new ArrayList<>();
for (MediaType mediaType : SUPPORTED_MEDIA_TYPES) {
dynamicTests.add(dynamicTest(mediaType.toString(),
() -> mockMvc.perform(post(builder.toString()).contentType(mediaType))
.andExpect(status().is(IsNot.not(415)))));
}
dynamicContainers.add(dynamicContainer(builder.toString(), dynamicTests));
}
}
}
return dynamicContainers;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment