How to testing Spring validator with Junit and Mockito - spring

I have a Spring Validator:
#Component
public class AddClientAccountValidator implements Validator {
#Autowired
private ValidatorUtils validatorUtils;
#Override
public boolean supports(Class<?> clazz) {
return UserDto.class.equals(clazz);
}
#Override
public void validate(Object target, Errors errors) {
UserDto user = (UserDto) target;
validatorUtils.setParam(errors, user);
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "username.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword",
"confirmPassword.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "firstName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "lastName.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "personalId", "personalId.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "city", "city.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "address.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "email.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "phone.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "contribution", "contribution.required");
validatorUtils.validateAddClientAccount();
}
}
In above Validator have inject to ValidatorUtils class:
#Component
class ValidatorUtils {
#Autowired
private PersonalIdValidator personalIdValidator;
private Errors errors;
private UserDto user;
void setParam(Errors errors, UserDto user) {
this.errors = errors;
this.user = user;
}
void validateAddClientAccount() {
validateAccount();
validContributionAccount();
}
private void validateAccount() {
validUsername();
validPassword();
validFirstName();
validLastName();
validPersonalId();
validCity();
validAddress();
validEmail();
validPhone();
}
public void validateChangePassword() {
validChangePassword();
}
private void validUsername() {
if (!user.getUsername().isEmpty()) {
String username = user.getUsername();
if ((username.length() < 3) || (username.length() > 40)) {
errors.rejectValue("username", "username.format");
}
}
}
private void validPassword() {
if (!user.getPassword().isEmpty()) {
String password = user.getPassword();
if ((password.length() < 3) || (password.length() > 40)) {
errors.rejectValue("password", "password.format");
}
if (!password.equals(user.getConfirmPassword())) {
errors.rejectValue("confirmPassword", "password.confirm");
}
}
}
private void validFirstName() {
if (!user.getFirstName().isEmpty()) {
String firstName = user.getFirstName();
String regex = "[A-ZŁ{1}]+[a-zł]+";
boolean validFirstName = Pattern.matches(regex, firstName);
if ((firstName.length() < 3) || (firstName.length() > 40) || !validFirstName) {
errors.rejectValue("firstName", "firstName.format");
}
}
}
private void validLastName() {
if (!user.getLastName().isEmpty()) {
String lastName = user.getLastName();
String regex = "[A-ZĆŁŚŻŹ{1}]+[a-ząćęłńóśżź]+";
String regexWithTwoLastName = "[A-ZĆŁŚŻŹ{1}]+[a-ząćęłńóśżź]++[\\s]+[A-ZĆŁŚŻŹ{1}]+[a-ząćęłńóśżź]+";
boolean validLastName = Pattern.matches(regex, lastName);
boolean validWithTwoLastName = Pattern.matches(regexWithTwoLastName, lastName);
if ((lastName.length() < 3) || (lastName.length() > 40)
|| (!validLastName && !validWithTwoLastName)) {
errors.rejectValue("lastName", "lastName.format");
}
}
}
this class have more validator for field but I skipped it.
I want to test my Validator class use Junit or eventually mockito. I write this test class:
#RunWith(MockitoJUnitRunner.class)
public class AddClientAccValidatorTest {
#InjectMocks
private AddClientAccountValidator validator;
#Mock
private ValidatorUtils validatoUtils;
private UserDto userDto;
public Errors errors;
#Before
public void setUp() {
UserDto userDto = new UserDto();
errors = new BeanPropertyBindingResult(userDto, "userDto");
}
#Test
public void testValidate() {
validator.validate(userDto, errors);
assertFalse(errors.hasErrors());
}
}
But when i run my test i get following Failet trace:
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:86)
at org.junit.Assert.assertTrue(Assert.java:41)
at org.junit.Assert.assertFalse(Assert.java:64)
at org.junit.Assert.assertFalse(Assert.java:74)
at pl.piotr.ibank.validator.AddClientAccValidatorTest.testValidate(AddClientAccValidatorTest.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Why I get this error? I get error in this line:
errors = new BeanPropertyBindingResult(userDto, "userDto");
And my second problem is that I can't declare multiple RunWith annotation. When I add:
#RunWith(MockitoJUnitRunner.class)
I can't parametrized my test using #RunWith(Parameterized.class)
How to solve it?
Anyone can help me? Maybe my approach is bad? What is best way to test Spring Validator with Junit?

You can run your test successfully without Mockito. The following code works with Spring #Configuration class (spring-test as dependency is required):
package foo.bar;
import static org.junit.Assert.assertFalse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class AddClientAccValidatorTest {
#Configuration
static class ContextConfiguration {
#Bean
public AddClientAccountValidator validator() {
return new AddClientAccountValidator();
}
#Bean
public ValidatorUtils validatorUtils() {
return new ValidatorUtils();
}
}
#Autowired
private AddClientAccountValidator validator;
private UserDto userDto;
public Errors errors;
#Before
public void setUp() {
userDto = new UserDto();
userDto.setLastName("Doe");
userDto.setFirstName("John");
userDto.setUsername("username");
userDto.setPhone("phone");
userDto.setPassword("password");
userDto.setConfirmedPassword("password");
userDto.setEmail("email");
userDto.setContribution("contribution");
userDto.setAddress("address");
userDto.setCity("city");
userDto.setPersonalId("personalId");
errors = new BeanPropertyBindingResult(userDto, "userDto");
}
#Test
public void testValidate() {
validator.validate(userDto, errors);
assertFalse(errors.hasErrors());
}
}

You don't need to Mock anything. While validating , we need the object which we want to validate and the errors. Create an object with required fields to validate and the errors object. For example,
#Test
public void shouldReturnErrorsWhenCustomObjectIsNull() {
CustomValidator customValidator = new CustomValidator();
Employee employee = new Employee();
employee.setEmployeeFirstname("empName")
Errors errors = new BeanPropertyBindingResult(employee, "employee");
customValidator.validate(employee, errors);
List<ObjectError> allErrors = errors.getAllErrors();
assertTrue("Errors list size should not be null : ", allErrors.size() > 0);
assertTrue(errors.hasErrors());
assertNotNull( errors.getFieldError("empName") );
}

Related

Vaadin BeanCreationException: during trying to call save method of my service class

Hi I have a little Vaadin project. In there, I've a UserUtils.class which has a createNewUser method which looks like this:
LoginView:
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.login.LoginForm;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Collections;
import static com.packagename.utils.UserUtils.createNewUser;
#Route("login")
#PageTitle("Login - packagename")
public class LoginView extends VerticalLayout implements BeforeEnterObserver {
private LoginForm login = new LoginForm();
private PasswordEncoder passwordEncoder;
public LoginView(){
createNewUser("daniel.tran", "cAWFCMaa22", true, "ADMIN");
addClassName("login-view");
setSizeFull();
setAlignItems(Alignment.CENTER);
setJustifyContentMode(JustifyContentMode.CENTER);
login.setAction("login");
add(
new H1("Willkommen!"),
login
);
}
#Override
public void beforeEnter(BeforeEnterEvent event) {
// Inform the user about an authentication error
if (!event.getLocation()
.getQueryParameters()
.getParameters()
.getOrDefault("error", Collections.emptyList())
.isEmpty()) {
login.setError(true);
}
}
}
UserUtils.class:
import com.packagename.backend.entity.UserEntity;
import com.packagename.backend.service.UserService;
import com.packagename.security.SecurityConfiguration;
import com.packagename.ui.views.login.LoginView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
public class UserUtils {
#Autowired
private LoginView loginView;
private static UserService userService;
private PasswordEncoder passwordEncoder;
public static void createNewUser(String pUsername, String pPassword, boolean pStatus, String pRole) {
if (!UserUtils.userExists(pUsername)) {
userService = new UserService();
PasswordEncoder passwordEncoder = SecurityConfiguration.passwordEncoder();
String encodedPassword = passwordEncoder.encode(pPassword);
UserEntity user = new UserEntity();
user.setUserName(pUsername);
user.setPassword(encodedPassword);
user.setStatus(pStatus);
user.setRoles(pRole);
userService.save(user);
}
}
private static boolean userExists(String pUsername) {
userService = new UserService();
UserEntity user = new UserEntity();
user.setUserName(pUsername);
boolean exists = userService.exists(user);
return exists;
}
}
UserService.class:
import com.packagename.backend.entity.UserEntity;
import com.packagename.backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
#Service
public class UserService {
private UserRepository userRepository;
private Logger LOGGER;
#Autowired
public UserService(UserRepository pUserRepository) {
this.userRepository = pUserRepository;
}
public UserService() {}
public List<UserEntity> findAll() {
return userRepository.findAll();
}
public long count() {
return userRepository.count();
}
public void delete(UserEntity user) {
userRepository.delete(user);
}
public void save(UserEntity user) {
if (user == null) {
LOGGER.log(Level.SEVERE, "Contact is null. Are you sure you have connected your form to the application?");
return;
}
userRepository.save(user);
}
public boolean exists(UserEntity user) {
Example<UserEntity> example = Example.of(user);
boolean exists = userRepository.exists(example);
return exists;
}
}
UserEntity.class:
import javax.persistence.*;
#Entity
#Table(name = "PSYS_USERS")
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int userid;
private String userName;
private String password;
private boolean status;
private String roles;
public UserEntity(){}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
}
UserRepository.class
import com.packagename.backend.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<UserEntity, Integer> {
Optional<UserEntity> findByUserName(String userName);
}
And always when it comes to the situtation, trying to call the userService methods, then it throws the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.packagename.ui.views.login.LoginView': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.packagename.ui.views.login.LoginView]: Constructor threw exception; nested exception is java.lang.NullPointerException
I tried to create a default constructor, at the entity and also at the service class but nothing want help.
So far,
Daniel
new UserService(); - this is the problem.
you cannot instantiate spring components on your own, you have to let spring inject/autowire them.
Places where you can inject Spring components are spring components themselves, and with Vaadin, you can inject in your views that have a #Route annotation. LoginView is such a view. So there you inject the UserService, and pass it along to the createNewUser method.
// LoginView constructor
// userService is injected/autowired this way
public LoginView(UserService userService){
createNewUser("daniel.tran", "cAWFCMaa22", true, "ADMIN", userService);
addClassName("login-view");
setSizeFull();
setAlignItems(Alignment.CENTER);
setJustifyContentMode(JustifyContentMode.CENTER);
login.setAction("login");
add(
new H1("Willkommen!"),
login
);
}
// UserUtils
public static void createNewUser(String pUsername, String pPassword, boolean pStatus, String pRole, UserService userService) {
if (!UserUtils.userExists(pUsername, userService)) {
PasswordEncoder passwordEncoder = SecurityConfiguration.passwordEncoder();
String encodedPassword = passwordEncoder.encode(pPassword);
UserEntity user = new UserEntity();
user.setUserName(pUsername);
user.setPassword(encodedPassword);
user.setStatus(pStatus);
user.setRoles(pRole);
userService.save(user);
}
}
private static boolean userExists(String pUsername, UserService userService) {
UserEntity user = new UserEntity();
user.setUserName(pUsername);
boolean exists = userService.exists(user);
return exists;
}
By the way, UserUtils is not a Spring Component so you cant autowire the loginView there either - good thing it's not used anyway

Spring Boot request validation

I've been reading a lot about spring request validation. I read a lot articles on how to appropriately implement that, but I have some problem. This is my code:
RestController:
#Autowired
EmployeeManager employeeManager;
#Autowired
EmployeeValidator employeeValidator;
#InitBinder("employee")
public void setupBinder(WebDataBinder binder) {
binder.addValidators(employeeValidator);
}
// -------------- CREATE EMPLOYEES --------------
#PostMapping(value = "add")
public ResponseEntity<EmployeeDTO> addEmployee(#Valid #RequestBody EmployeeDTO employee) {
boolean isCreated = employeeManager.addEmployee(employee);
if(isCreated) {
return new ResponseEntity<>(employee, HttpStatus.CREATED);
}
return new ResponseEntity(new CustomError("Unable to create, employee with email " +
employee.getEmail() + " already exist."), HttpStatus.CONFLICT);
}
Validator:
package com.employee.api.EmployeeAPI.validator;
import com.employee.api.EmployeeAPI.model.dto.EmployeeDTO;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
#Component
public class EmployeeValidator implements Validator {
private Pattern pattern;
private Matcher matcher;
private static final String STRING_PATTERN = "[a-zA-Z]+";
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
#Override
public boolean supports(Class<?> clazz) {
return EmployeeDTO.class.equals(clazz);
}
#Override
public void validate(Object target, Errors errors) {
EmployeeDTO employee = (EmployeeDTO) target;
if (validateInputString(employee.getFirstName(), STRING_PATTERN)) {
errors.rejectValue("firstName", "firstName.invalid");
}
if (validateInputString(employee.getLastName(), STRING_PATTERN)) {
errors.rejectValue("lastName", "lastName.invalid");
}
if (validateInputString(employee.getJob(), STRING_PATTERN)) {
errors.rejectValue("job", "job.invalid");
}
if (validateInputString(employee.getEmail(), EMAIL_PATTERN)) {
errors.rejectValue("email", "email.invalid");
}
}
private boolean validateInputString(String input, String regexPattern) {
pattern = Pattern.compile(regexPattern);
matcher = pattern.matcher(input);
return (!matcher.matches() || input == null || input.trim().length() == 0);
}
}
and in config I added bean:
#Bean
public EmployeeValidator beforeAddOrUpdateEmployeeValidator() {
return new EmployeeValidator();
}
I am not really sure of how it should be invoked right now when adding employees, because it surely does not work for now. Could you help me with the right implementation or point in the right direction?
I'm not familiar with org.springframework.validation.Validator, but will suggest you how to do the same validation as you need with javax.validation.ConstraintValidator (JSR-303). Your controller class is fine and no changes needed there.
you need to create a custom annotation #ValidEmployee and annotate your dto with it:
#ValidEmployee
public class EmployeeDto {
...
}
ValidEmployee annotation:
import javax.validation.Constraint;
import javax.validation.Payload;
#Target({TYPE, ANNOTATION_TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = EmployeeValidator.class)
#Documented
public #interface ValidEmployee {
String message() default "{ValidEmployee.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
and implement your validation logic in isValid method:
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class EmployeeValidator implements ConstraintValidator<ValidEmployee, EmployeeDto> {
#Override
public void initialize(ValidEmployee constraintAnnotation) {
}
#Override
public boolean isValid(EmployeeDto employee, ConstraintValidatorContext context) {
// do your validation logic
}
}

Spring Boot - Test - Validator: Invalid target for Validator

I'm getting the following error when I'm trying to run a test:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Invalid target for Validator [userCreateFormValidator bean]: com.ar.empresa.forms.UserCreateForm#15c3585
Caused by: java.lang.IllegalStateException: Invalid target for Validator [userCreateFormValidator bean]: com.ar.empresa.forms.UserCreateForm#15c3585
at org.springframework.validation.DataBinder.assertValidators(DataBinder.java:567)
at org.springframework.validation.DataBinder.addValidators(DataBinder.java:578)
at com.ar.empresa.controllers.UserController.initBinder(UserController.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
The code is:
Controller:
#Controller
public class UserController {
private UserService userService;
private UserCreateFormValidator userCreateFormValidator;
#Autowired
public UserController(UserService userService, UserCreateFormValidator userCreateFormValidator) {
this.userService = userService;
this.userCreateFormValidator = userCreateFormValidator;
}
#InitBinder("form")
public void initBinder(WebDataBinder binder) {
binder.addValidators(userCreateFormValidator);
}
#PreAuthorize("hasAuthority('ADMIN')")
#RequestMapping(value = "/user/create", method = RequestMethod.GET)
public ModelAndView getUserCreatePage() {
return new ModelAndView("user_create", "form", new UserCreateForm());
}
#PreAuthorize("hasAuthority('ADMIN')")
#RequestMapping(value = "/user/create", method = RequestMethod.POST)
public String handleUserCreateForm(#Valid #ModelAttribute("form") UserCreateForm form, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "user_create";
}
try {
userService.create(form);
} catch (DataIntegrityViolationException e) {
bindingResult.reject("email.exists", "Email already exists");
return "user_create";
}
return "redirect:/users";
}
}
Validator:
#Component
public class UserCreateFormValidator implements Validator {
private final UserService userService;
#Autowired
public UserCreateFormValidator(UserService userService) {
this.userService = userService;
}
#Override
public boolean supports(Class<?> clazz) {
return clazz.equals(UserCreateForm.class);
}
#Override
public void validate(Object target, Errors errors) {
UserCreateForm form = (UserCreateForm) target;
validatePasswords(errors, form);
validateEmail(errors, form);
}
private void validatePasswords(Errors errors, UserCreateForm form) {
if (!form.getPassword().equals(form.getPasswordRepeated())) {
errors.reject("password.no_match", "Passwords do not match");
}
}
private void validateEmail(Errors errors, UserCreateForm form) {
if (userService.getUserByEmail(form.getEmail()).isPresent()) {
errors.reject("email.exists", "User with this email already exists");
}
}
}
UserCreateForm:
public class UserCreateForm {
#NotEmpty
private String email = "";
#NotEmpty
private String password = "";
#NotEmpty
private String passwordRepeated = "";
#NotNull
private Role role = Role.USER;
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public String getPasswordRepeated() {
return passwordRepeated;
}
public Role getRole() {
return role;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
public void setPasswordRepeated(String passwordRepeated) {
this.passwordRepeated = passwordRepeated;
}
public void setRole(Role role) {
this.role = role;
}
}
Test:
#RunWith(SpringRunner.class)
#SpringBootTest
public class UserControllerTest {
private MockMvc mockMvc;
private MediaType contentType = new MediaType(APPLICATION_JSON.getType(),
APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
#MockBean
private UserService userService;
#MockBean
private UserCreateFormValidator userCreateFormValidator;
#Autowired
FilterChainProxy springSecurityFilterChain;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(new UserController(userService,userCreateFormValidator)).apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain)).build();
}
#Test
#WithMockUser(username="user",
password="password",
roles="ADMIN")
public void homePage_authenticatedUser() throws Exception {
mockMvc.perform(get("/user/create"))
.andExpect(status().isOk())
.andExpect(view().name("user_create"));
}
}
I don't know why, because it is a GET method, so it don't have to validate it.
Thanks! :)
You got this exception because you didn't mock the behaviour of public boolean supports(Class<?> clazz) method on your userCreateFormValidator #Mockbean.
If you take a look at the code of org.springframework.validation.DataBinder.assertValidators(DataBinder.java) from the log you posted, you can find there how the validators are processed and how java.lang.IllegalStateException is thrown. In Spring 4.3.8, it looks like this
if(validator != null && this.getTarget() != null && !validator.supports(this.getTarget().getClass())) {
throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + this.getTarget());
}
You didn't mock supports method of the validator and returns false by default, causing Spring code above throw the IllegalStateException.
TLDR, just give me solution:
You have to mock supports method on your validator. Add following to #Before or #BeforeClass method.
when(requestValidatorMock.supports(any())).thenReturn(true);
I cant comment on the correct answer but his solution worked:
Here is what I had to do for this exact error.
//Imports
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
#MockBean
ApiValidationRouter apiValidationRouter;
#Before
public void beforeClass() throws Exception {
when(apiValidationRouter.supports(any())).thenReturn(true);
}

Spring boot configure MessageInterpolator #Bean

I am using Spring boot v1.4 and hibernate v4.3.5.finall in my application
I have writen my own ResourceBundle and MessageInterpolator to save messages in database and have configured them as bean in my project. It seems ResourceBundle works fine and returns my custom message but parameters don't pass,for example for this validation :
#Size(min=5,max = 10)
private String lastName;
I expect : size must be between 5 and 10 bla bla.....
but the result is : size must be between {min} and {max} bla bla.....
any Idea? Thanks..
my ResourceBundle class:
package ir.pt.core.bundles;
import ir.pt.common.bean.ResourceEntity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import java.io.IOException;
import java.util.*;
public class DatabaseResourceBundle extends ResourceBundle {
#PersistenceContext
protected EntityManager em;
private Map<String, String> cache = new HashMap<String, String>();
protected final static String BUNDLE_NAME = "ir.pt.core.bundles";
protected Control DB_CONTROL = new DBControl();
public DatabaseResourceBundle() {
setParent(ResourceBundle.getBundle(BUNDLE_NAME, DB_CONTROL));
}
public DatabaseResourceBundle(Locale locale) {
setParent(ResourceBundle.getBundle(BUNDLE_NAME, locale, DB_CONTROL));
}
#Override
protected Object handleGetObject(String key) {
return cache != null ? cache.get(key) : parent.getObject(key);
}
#Override
public Enumeration<String> getKeys() {
return parent.getKeys();
}
protected class DBControl extends Control {
#Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException {
return new CustomizedLocaleResources(locale);
}
protected class CustomizedLocaleResources extends ListResourceBundle {
private Locale locale;
public CustomizedLocaleResources(Locale locale) {
this.locale = locale;
}
#Override
protected Object[][] getContents() {
String sql = "FROM ResourceEntity re WHERE re.locale = '"+locale.getLanguage()+"'";
TypedQuery<ResourceEntity> query =
em.createQuery(sql, ResourceEntity.class);
List<ResourceEntity> resources = query.getResultList();
Object[][] all = new Object[resources.size()][2];
int i = 0;
for (Iterator<ResourceEntity> it = resources.iterator(); it.hasNext();) {
ResourceEntity resource = it.next();
all[i] = new Object[]{resource.getKey(), resource.getMessage()};
cache.put(resource.getKey(), resource.getMessage());
i++;
}
return all;
}
}
}
}
my MessageInterpolator class:
package ir.pt.core.bundles;
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.MessageInterpolator;
import java.util.Locale;
import java.util.Map;
public class DatabaseMessageInterpolator extends ResourceBundleMessageInterpolator implements MessageInterpolator{
protected final String BRACE_OPEN = "\\{";
protected final String BRACE_CLOSE = "\\}";
#Autowired
DatabaseResourceBundle databaseResourceBundle;
#Override
public String interpolate(String message, Context context) {
return interpolate(message, context, databaseResourceBundle.getLocale());
}
#Override
public String interpolate(String message, Context context, Locale locale) {
String messageKey = context.getConstraintDescriptor().getAttributes().get("message").toString();
message = databaseResourceBundle.getString(messageKey.replaceAll(BRACE_OPEN, "").replaceAll(BRACE_CLOSE, ""));
Map<String, Object> attributes = context.getConstraintDescriptor().getAttributes();
for (String key : attributes.keySet()) {
String value = attributes.get(key).toString();
key = BRACE_OPEN + key + BRACE_CLOSE;
message = message.replaceAll(key, value);
}
return message;
}
}
my bean configuration:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurationSupport {
#Override
public Validator getValidator() {
LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
factory.setMessageInterpolator(messageInterpolator());
return factory;
}
#Bean
public MessageInterpolator messageInterpolator() {
return new DatabaseMessageInterpolator();
}
#Bean
ResourceBundle resourceBundle() {
return new DatabaseResourceBundle(new Locale("fa"));
}
}

Testing Spring Boot REST json result

I have some problem with checking json result
UserControllerTest class
package com.serwis.controller;
import com.serwis.PraktykiApplication;
import com.serwis.model.User;
import com.serwis.repository.UserRepository;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(PraktykiApplication.class)
#WebIntegrationTest
public class UserControllerTests {
#Autowired
private UserRepository userRepository;
User user;
private MockMvc mockMvc;
#Before
public void setUp(){
user = new User("login1","password","email");
userRepository.deleteAll();
userRepository.save(user);
this.mockMvc = standaloneSetup(new UserController()).build();
}
#Test
public void createUser() throws Exception {
this.mockMvc.perform(get("/user/findall/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.login", is("login1")));
System.out.println(userRepository.findAll());
}
}
User class
package com.serwis.model;
import javax.persistence.*;
import java.util.Arrays;
import java.util.Set;
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="id")
private long id;
#Column(name="login")
private String login;
#Column(name="password")
private String password;
#Column(name="email")
private String email;
#Column(name="avatar")
private byte[] avatar;
public User(){}
public User(String login, String password, String email) {
this.login = login;
this.password = password;
this.email = email;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", avatar=" + Arrays.toString(avatar) +
'}';
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public byte[] getAvatar() {
return avatar;
}
public void setAvatar(byte[] avatar) {
this.avatar = avatar;
}
}
UserRepository class
package com.serwis.repository;
import com.serwis.model.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
#Transactional
public interface UserRepository extends CrudRepository<User, Long>{
}
userController class
package com.serwis.controller;
import com.serwis.model.User;
import com.serwis.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by Jodanpotasu on 2016-07-24.
*/
#Controller
public class UserController {
#Autowired
private UserRepository userRepository;
#RequestMapping("/user/create")
#ResponseBody
public String create(String email, String login, String password) {
String userId = "";
try {
User user = new User(email, login, password);
userRepository.save(user);
userId = String.valueOf(user.getId());
} catch (Exception ex) {
return "Error creating the user: " + ex.toString();
}
return "User succesfully created with id = " + userId;
}
#RequestMapping("/user/findall/")
#ResponseBody
public Iterable<User> findAll() {
return userRepository.findAll();
}
#RequestMapping("/user/delete")
#ResponseBody
public String delete(long id) {
User deleted = userRepository.findOne(id);
userRepository.delete(id);
return "USER DELETED: " + deleted;
}
#RequestMapping("/user/update")
#ResponseBody
public String update(long id, String login, String password, String email) {
User beforeUpdate = userRepository.findOne(id);
User afterUpdate = userRepository.findOne(id);
afterUpdate.setLogin(login);
afterUpdate.setEmail(email);
afterUpdate.setPassword(password);
return "BEFORE UPDATE: \n" + beforeUpdate + " <br> AFTER UPDATE: " + afterUpdate;
}
}
it should be like
[{"id":1,"login":"login1","password":"password","email":"email","avatar":null}]
But i still have error output
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
and that is full output
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at com.serwis.controller.UserControllerTests.createUser(UserControllerTests.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:253)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.NullPointerException
at com.serwis.controller.UserController.findAll(UserController.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
... 43 more
Spring boot version: 1.3.6 is there another better way to test json?
Here is my working class
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(PraktykiApplication.class)
#WebIntegrationTest
public class UserControllerTests {
#Autowired
private UserRepository userRepository;
User user;
private MockMvc mockMvc;
#Autowired
UserController userController;
#Before
public void setUp(){
user = new User("login1","password","email");
userRepository.deleteAll();
userRepository.save(user);
this.mockMvc = standaloneSetup(userController).build();
}
#Test
public void createUser() throws Exception {
this.mockMvc.perform(get("/user/findall/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$[0].login", is("login1")));
System.out.println(userRepository.findAll());
}
}
it seems that spring boot did not see
this.mockMvc = standaloneSetup(new UserController()).build();

Resources