Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.