Sekhar
Sekhar

Reputation: 1001

writing junit for custom spring validator class

How to write a unit testing case for custom spring validator implementation class . For example

public class RegistrationValidator implements Validator.

Just wanted to know the various approaches . Am new to spring so exploring all options.

Thanks, S

Upvotes: 1

Views: 1401

Answers (1)

Ralph
Ralph

Reputation: 120771

Create an Errors object, Create an instance of your Validator,

invoke yourValidator(testData, errors)

Check that Errors is modified in the way you expected, in dependence to testData

@Test
public void testValidateWithUserWithoutLogin() {
    User u = new User(); //your domain object, for example a user with "login=null"

    Errors errors = new BeanPropertyBindingResult(u, "u");

    MyValidator validator = newValidator();

    validator.validate(p, errors);  // 'validator' under test

    assertTrue(errors.hasErrors());
    assertNotNull( errors.getFieldError("login") );
}

BTW: you should have a look at JSR 303-Bean Validation, it is also supported by Spring 3.0. But it is easyer to use (less code) for the most use cases.

Upvotes: 3

Related Questions