i've been reading hibernate docs class validation tests , did not found solution "problem". test custom validators. example, let's have following class:
public class user { @notempty(message = "{username.notspecified}") private string username; @notempty @size(min = 6, message = "{password.tooshort") private string password; @notempty(message = "{city.notspecified}") private string city; /* getters & setters omitted */ }
and want check every user located in barcelona city. that, have custom user validator implementation follows:
public class uservalidator implements validator { @autowired private validator validator; @override public boolean supports(class<?> clazz) { return user.class.equals(clazz); } @override public void validate(object target, errors errors) { validator.validate(target,errors); user user = (user) target; if(!(user.getcity().equals("barcelona"))){ errors.rejectvalue("city", "city.notvalid", "invalid city"); } } }
i have no idea how use custom validator instead of default 1 provided in example , checks annotated field constraints , not more "business logic" ones. examples or clues on that?
thanks!
you don't have implement spring validator unit testing, create javax.validation.validator instance it.
import static org.hamcrest.matchers.*; import static org.junit.assert.*; import java.util.*; import javax.validation.*; import org.junit.*; public class applierdtounittests { private validator validator = validation.buildvalidatorfactory().getvalidator(); private applierdto target = new applierdto(); @test public void brokenifnullnamegiven() throws exception { target.setname(null); set<constraintviolation<applierdto>> constraintviolations = validator .validate(target); assertthat("unexpected size of constraint violations", constraintviolations.size(), equalto(1)); } }
and use validators validate form or rpc request rather "business logic" in expierence. they're not easy use in domain layer point of view.
Comments
Post a Comment