如何在Spring Boot应用中测试验证器?

时间:2019-04-25 18:41:30

标签: java spring spring-boot validation junit

我有一堂课

@Component
public class ContractorFormValidator implements Validator {

    Logger logger = LoggerFactory.getLogger(ContractorFormValidator.class);

    @Inject IBusinessDataValidator businessDataValidator;

    @Override
    public boolean supports(Class<?> clazz) {
        return Contractor.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Contractor contractor = (Contractor) target;
        if (!businessDataValidator.isNipValid(contractor.getContractorData().getNip())) {
            errors.rejectValue("contractorData.nip", "invalid");
        }
        if (!businessDataValidator.isRegonValid(contractor.getContractorData().getRegon())) {
            errors.rejectValue("contractorData.regon", "invalid");
        }
    }
}

我该如何测试?我已经尝试过:How to test validation annotations of a class using JUnit?,但这不起作用,因为验证器中的validate方法要求将Errors类传递给它的方法签名。

我不知道是否可以将此Errors对象传递给验证程序。还有其他办法吗?

2 个答案:

答案 0 :(得分:1)

您是否尝试过为此编写简单的单元测试?

@RunWith(SpringJUnit4ClassRunner.class)
public class ContractorFormValidatorTest {

  @Autowired
  private ContractorFormValidator validator;

  @Test
  public void testValidation() throws Exception {
    Contractor contractor = new Contractor();
    // Initialise the variables here.

    Errors errors = new BeanPropertyBindingResult(contractor, "contractor");
    validator.validate(contract, errors);

    // If errors are expected.
    Assert.assertTrue(errors.hasErrors());

   for (Error fieldError : errors.getFieldErrors()) {
       Assert.assertEquals("contractorData.nip", fieldError.getCode());
   }
  }
}

如果要在控制器实现中使用验证器,则需要使用MockMvc API

您的设置可以包含在上面的课程中。

private MockMvc mockMvc

@Autowired
private MyController controller;

@Before
public void setUp() throws Exception {
  this.mockMvc = MockMvcBuilders.standaloneSetup(this.controller).build();
}

@Test
public void testMethod() {
   MvcResult result = this.mockMvc.perform(MockMvcRequestBuilders.post("/yoururl")).
    andExpect(MockMvcResultMatchers.status().isCreated()).andReturn();
}

答案 1 :(得分:0)

使用org.springframework.validation.BeanPropertyBindingResult类,

Errors newErrors = new BeanPropertyBindingResult(validateObject, "objectName");