Spring MVC / Hybris JUnit For Validators

Hi Guys ,today I am going to write a post on Test Validators in Spring MVC with Junit or How to write Junit for Validators.
I faced quite a lot problem in finding a proper solution for that while working in a project . These Validators are used
in Spring MVC and Hybris projects . So Basically while writting a Validator I had to check 2 main things 1st was that expiry date should not be null and
other was the file uploaded in form should have valid format and lesser than 5MB in size. so My Validator method looks as below:




@Override
public void validate(final Object object, final Errors errors)
{
final myForm myForm = (myForm) object;

 if (!checkFileContentType(myForm.getFileScan().getContentType())
{
errors.rejectValue("file", "File is Invalid");
}


if (myForm.getExpiryDate() == null || myForm.getExpiryDate().equals(""))
{
errors.rejectValue("date", "Invalid date");
}

}





so for JUnit of this validator i need to varify errors.rejectValue as feel upload a dummy file with java code in my validtor class.
So my Test class looks as below :






MyValidator = new MyValidator();
}

@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);// this line is optional if not using mockito

MyForm myForm= new MyForm();
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File file = new File(path + "abc.jpeg");
FileItem fi = this.createFileItem("file", file);
CommonsMultipartFile FileScan = new CommonsMultipartFile(fi);
myForm.setFileScan(FileScan);
}



@Test
public void testdatenull()
{

myForm.setFileName("testFileName");
myForm.setExpiryDate(null);
final BindException errors = new BindException(myForm, myForm.class.getName());
MyValidator.validate(myForm, errors);

assertEquals("Invalid date", errors.getFieldError("date").getCode());


}

@Test
public void testEmptyFileScan()
{
MyForm myNewForm= new MyForm();
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
File file = new File(path + "abc.xml");
FileItem fi = this.createFileItem("file", file);
CommonsMultipartFile newFileScan = new CommonsMultipartFile(fi);
myNewForm.setFileScan(newFileScan);
myNewForm.setFileName(StringUtils.EMPTY);
myNewForm.setExpiryDate("15/08/2013");
final BindException errors = new BindException(myNewForm, MyForm.class.getName());
MyValidator.validate(myNewForm, errors);
assertEquals("File is invalid", errors.getFieldError("file").getCode());


}

private FileItem createFileItem(final String fieldName, final File file) throws Exception
{

final boolean isFormField = false;
final String fileName = file.getName();
final String contentType = new MimetypesFileTypeMap().getContentType(file);

final DiskFileItemFactory factory = new DiskFileItemFactory();
final FileItem fileItem = factory.createItem(fieldName, contentType, isFormField, fileName);

final InputStream input = new FileInputStream(file);
final OutputStream output = fileItem.getOutputStream();

IOUtils.copy(input, output);

IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);

return fileItem;
}





1. In method createFileItem I created a dummy file to send as parameter to my validate method . In test methods I am using
two differen files test.txt and test.jpg as my validtor allows only media file so test.txt is to check the failing criteria.

2. to check error.rejectValue in junit I have used assertEquals . It conatins 2 parameters first is the String and other one is the
value set in Errors object by validator .errors.getFieldError("date") in this the fieldName date is same as given in validator for errors.setrejectValue.


I hope this post helps .If someone has a better code or enhancements that can b done please comment below or also write a mail to admin@javainhouse.com

Spring MVC Validations Tutorial


Hi friends,Today I am going to tell you about spring validations . Validations are important part of any application  are applied on the input given by user.In Spring there are some predefined validations which we can use in our application.

Let us first execute the project step by step and at last I ll explain you the steps in detail. In same manner as I show you in Spring MVC Hello World Tutorial , we ll create a new Dynamic Project . I f you haven't read about Spring Basics like Spring Flow and Basic Hello World Program the I  ll advise you to first go through them . Now let us learn validations step by step .


What you ll require :

1.validation-api-1.0.0.[JSR-303]

2.hibernate-validator-4.2.0.Final


  • Spring annotation validations are also known as JSR-303 validations
  • We need to import javax.validation.constraints.* and org.hibernate.validator.constraints.*



Step 1: As we have some bean class as:

import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Size;
public class JavaInHouseBean{

    @NotEmpty
    private String user;

    @NotEmpty(message = "Password should not be blank.")
    @Size(min = 5, max = 8, message = "Password length should be between 5 to 8 Characters.")
    private String password;

    // Setters and Getters...
}



Step 2: Controller class :

@Controller
public class JavaInHouseController {  

        @RequestMapping("/login")
        public String loginCheck(@Valid JavaInHouseBean bean, BindingResult result, ModelMap model) {

            if (result.hasErrors()) {
                return "loginPage";
            } else {
                model.addAttribute("loginobj", bean);
                return "success";
            }
        }            
}

Step 3:  In spring configuration file means file which is *-spring.xml you need to add

<mvc:annotation-driven />  so that JSR-303 annotations ll be activated.

after line <context:component-scan base-package="javainhouse" />


Now your validations should work perfectly and error message should be shown on view.

Explanation : In JavaInHouseController.java , I have written @Valid JavaInHouseBean bean right, means once the flow came to this line and as we are using @Valid annotation, flow will redirect to JavaInHouseBean and annotation validations will be executed. If  get any errors all those errors will be added to the BindingResult object automatically.  We can consider this BindingResult object as response in java servlets.

If you are facing any errors or any suggestions please comment below :)