lundi 27 avril 2015

Using Rest-assured to test Spring's controller with custom validation

I would like to test my JSON responses from Spring's controllers with Rest-assured. Everything works fine, even with @Valid annotation until I add custom annotation (@Unique)

Usage of problematic annotation

@Unique(service = UserExistentFieldService.class, fieldName = "email", message = "User.Mail.Unique")
private String mail;

CustomValidator looks like this:

public class UniqueValidator implements ConstraintValidator<Unique, Object> {

  private ExistentFieldService existentFieldService;
  private String fieldName;

  @Override
  public void initialize(Unique unique) {
      fieldName = unique.fieldName();
      existentFieldService = (ExistentFieldService) ApplicationContextProvider.getBean(unique.service());
  }

  @Override
  public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
      return !existentFieldService.isExists(fieldName, o);
  }
}

And ApplicationContextProvider:

@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    private static  ApplicationContext CONTEXT;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        ApplicationContextProvider.CONTEXT = context;
    }

    public static Object getBean(Class clazz) {
        return ApplicationContextProvider.CONTEXT.getBean(clazz.getSimpleName());
    }

    public static Object getBean(String qualifier, Class clazz) {
        return ApplicationContextProvider.CONTEXT.getBean(qualifier , clazz);
    }

}

I'm using Mockito for mocking the service layer, but I can't figure out how to mock UniqueValidator or ApplicationContextProvider. My @Before method contains

RestAssuredMockMvc.standaloneSetup(MockMvcBuilders.standaloneSetup(userController)
            .setValidator(new LocalValidatorFactoryBean()));

And test calls

given()
    .contentType("application/json")
    .body(userDto)
.when()
    .post("user/create", param)
.then().statusCode(HttpServletResponse.SC_OK);

NPE is thrown inside ApplicationContextProvider on line return ApplicationContextProvider.CONTEXT.getBean(clazz.getSimpleName()); because CONTEXT is null.

Is there any way how to mock Spring's validator or how to turn it off?

Aucun commentaire:

Enregistrer un commentaire