How to test validation annotations of a class using JUnit?

后端 未结 9 1131
盖世英雄少女心
盖世英雄少女心 2020-12-07 17:29

I need to test the validation annotations but it looks like they do not work. I am not sure if the JUnit is also correct. Currently, the test will be passed but as you can s

9条回答
  •  萌比男神i
    2020-12-07 18:05

    There are 2 things that you need to check:

    The validation rules are configured correctly

    The validation rules can be checked the way others advise - by creating a validator object and invoking it manually:

    Validator validator = Validation.buildDefaultValidatorFactory().getValidator()
    Set violations = validator.validate(contact);
    assertFalse(violations.isEmpty());
    

    With this you should check all the possible cases - there could be dozens of them (and in this case there should be dozens of them).

    The validation is triggered by the frameworks

    In your case you check it with Hibernate, therefore there should be a test that initializes it and triggers some Hibernate operations. Note that for this you need to check only one failing rule for one single field - this will be enough. You don't need to check all the rules from again. Example could be:

    @Test(expected = ConstraintViolationException.class)
    public void validationIsInvokedBeforeSavingContact() {
      Contact contact = Contact.random();
      contact.setEmail(invalidEmail());
      contactsDao.save(contact)
      session.flush(); // or entityManager.flush();
    }
    

    NB: don't forget to trigger flush(). If you work with UUIDs or sequences as an ID generation strategy, then INSERT is not going to be flushed when you save() - it's going to be postponed until later.

    This all is a part of how to build a Test Pyramid - you can find more details here.

提交回复
热议问题