Skip to content

Instantly share code, notes, and snippets.

@wkorando
Last active June 3, 2019 15:43
Show Gist options
  • Save wkorando/9ecd7d7fd7aab3bacad6fe0117367316 to your computer and use it in GitHub Desktop.
Save wkorando/9ecd7d7fd7aab3bacad6fe0117367316 to your computer and use it in GitHub Desktop.
public class TestAcceptedMediaTypes {
private static final MediaType[] SUPPORTED_MEDIA_TYPES = new MediaType[] { MediaType.APPLICATION_JSON,
MediaType.APPLICATION_XML };
@TestFactory
Collection<DynamicTest> testAcceptedMediaTypes() throws Exception {
// Creating a classpath scanner to find all controller classes in project
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(new DefaultListableBeanFactory(),
false);
scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));
Set<BeanDefinition> beanDefinitons = scanner.findCandidateComponents("com.bk.hotel");
Set<Object> controllers = new HashSet<>();
Set<Class<?>> controllersClasses = new HashSet<>();
// Instantiating controller classes
for (BeanDefinition beanDefiniton : beanDefinitons) {
String className = beanDefiniton.getBeanClassName();
Class<?> controllerClazz = ClassLoader.getSystemClassLoader().loadClass(className);
controllersClasses.add(controllerClazz);
Constructor<?> constructor = controllerClazz.getDeclaredConstructors()[0];
Object[] arguments = new Object[constructor.getParameterTypes().length];
int i = 0;
for (Class<?> parameterType : constructor.getParameterTypes()) {
arguments[i] = mock(parameterType);
i++;
}
controllers.add(constructor.newInstance(arguments));
}
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controllers.toArray()).build();
List<DynamicTest> generatedTests = 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)) {
for (MediaType mediaType : SUPPORTED_MEDIA_TYPES) {
generatedTests.add(dynamicTest(builder.toString() + " " + mediaType,
() -> mockMvc.perform(post(builder.toString()).accept(mediaType).contentType(mediaType))
.andExpect(status().is(IsNot.not(415)))));
}
}
}
}
return generatedTests;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment