0

Given a class:

public class Foo {

    @NotNull
    @Valid
    private Bar bar;    

    // plus getter/setter
}

Suppose I want to test that after the bar field is set, the class is now valid.

In my test, I'm using Mockito to get a fake Bar instance. I want this mockBar to be valid, without me having to worry about the particular field validations that Bar may contain.

Is there a Mockito way to make mockBar pass validation? Here's how I call validation in my test:

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
assertTrue(new ArrayList<>(validator.validate(foo)).isEmpty());

The javax.validation.Validator will recursively validate all fields of foo, so at some point the validator will do something with the mockBar. What do I need to mock to get this to return as valid?

Eric Wilson
  • 57,719
  • 77
  • 200
  • 270
  • I think you describing two conflicting requirements here. Either you want it to be valid, which means you need to take care of its fields values, or you don't want to validate it at all. But anyway, I'm interested if there is a solution to this :) – Benjamin Eckardt Jun 19 '20 at 20:46
  • I want the class under test (`foo`) to be valid. I don't want to have to worry about the validity of the members of that class -- I want to simply declare them valid, because I can test the validity of `bar` in a different unit test. – Eric Wilson Jun 19 '20 at 20:53
  • If `Validator` implementation internally used recursive calls for `@Valid` annotated embedded object you could spy on it and return empty List if type matches `Bar`. But this would be pretty brittle I'd say – Benjamin Eckardt Jun 19 '20 at 21:01

0 Answers0