Testing Spring Boot REST json result - spring

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();

Related

Usage of Config classes in integratiion testing scenario with #SpringJUnitConfig

I am trying to explore the Spring framework developing a very basic application based on one of my hobbies.
There is a null error when trying to execute a test that i am not really not understanding.
I have a Class tagged as a #Component:
package matchedbetting;
...
#Component("bet")
public class Bet {
private String team1;
private String team2;
...
public Bet(String team1, String team2, String league, double bookmaker, double exchange, double commission) {
super();
this.team1 = team1;
this.team2 = team2;
...
this.commission = commission;
}
#Autowired
public Bet() {
super();
}
}
I have a #Configuration class that imports another Configuration for aspects and scans for component in different packages:
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
#Configuration
#Import({AspectsConfig.class})
#ComponentScan({"matchedbetting","utils"})
public class MyTrainingConfig {
}
And in my test package i have a Config class that imports it:
package matchedbetting;
...
import config.MyTrainingConfig;
#Configuration
#Import({MyTrainingConfig.class})
public class MatchedBettingTestConfig {
#Bean MatchedBetting matchedBetting() {
return new MatchedBettingImpl();
}
}
Now i run my test and everything looks fine:
package matchedbetting;
...
import org.springframework.context.ConfigurableApplicationContext;
import utils.FieldConsistency;
public class MatchedBettingImplTests {
private ConfigurableApplicationContext context;
private Bet bet;
private FieldConsistency fieldConsistency;
private MatchedBetting matchedBetting;
#Before
public void setUp() {
context = SpringApplication.run(MatchedBettingTestConfig.class);
bet = context.getBean(Bet.class);
fieldConsistency = context.getBean(FieldConsistency.class);
matchedBetting = context.getBean(MatchedBetting.class);
}
#Test
public void test() {
setTestingBet(bet);
fieldConsistency.checkTeam(bet);
System.out.println("Rating Bet: " + matchedBetting.calculateRating(bet));
}
private void setTestingBet(Bet bet) {
bet.setTeam1("teamA");
...
bet.setCommission(0.01);
}
}
Now i am trying to switch to Spring testing :
package matchedbetting;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import utils.FieldConsistency;
#SpringJUnitConfig(classes=MatchedBettingTestConfig.class)
public class MatchedBettingImplTests {
#Autowired
private Bet bet;
#Autowired
private MatchedBetting matchedBetting;
#Autowired
private FieldConsistency fieldConsistency;
#Test
public void test() {
setTestingBet(bet);
fieldConsistency.checkTeam(bet);
System.out.println("Rating Bet: " + matchedBetting.calculateRating(bet));
}
private void setTestingBet(Bet bet) {
bet.setTeam1("teamA");
...
bet.setCommission(0.01);
}
}
But the test comes out with the error that "bet" is null. I really don't understand what i am missing.
java.lang.NullPointerException: Cannot invoke "matchedbetting.Bet.setTeam1(String)" because "bet" is null
at matchedbetting.MatchedBettingImplTests.setTestingBet(MatchedBettingImplTests.java:35)
at matchedbetting.MatchedBettingImplTests.test(MatchedBettingImplTests.java:28)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:93)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Any thoughts?
Thank you
Trying to switch integration testing using #SpringJUnitConfig
i was running the #Test as Junit4. Just switched to org.junit.jupiter.api.Test and now running the test as JUnit5 ends like expected
package matchedbetting;
import org.junit.jupiter.api.Test; //changed this
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import utils.FieldConsistency;
#SpringJUnitConfig(classes=MatchedBettingTestConfig.class)
public class MatchedBettingImplTests {
#Autowired
private Bet bet;
#Autowired
private MatchedBetting matchedBetting;
#Autowired
private FieldConsistency fieldConsistency;
#Test //changed this
public void test() {
setTestingBet(bet);
fieldConsistency.checkTeam(bet);
System.out.println("Rating Bet: " + matchedBetting.calculateRating(bet));
}
private void setTestingBet(Bet bet) {
bet.setTeam1("teamA");
bet.setBookmaker(1.5);
bet.setExchange(2);
bet.setCommission(0.01);
}
}

Mock test for Login Controller throwing null pointer exception for AuthenticationManager

I have an error when I try to create a post request in my Mock test. It tells me that the authenticationManager is null(meaning it wasn't autowired).
I have a Login Controller having an autowired AuthenticationManager with three methods(login/register/userinfo) .
I tried to create a Login Controller Test with an instance of LoginController having injectedMocks but I don't know how to use it(I am not accustomed to testing).
Login Controller
#RestController
#RequestMapping("/auth")
#CrossOrigin
public class LoginController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
JWTTokenHelper jWTTokenHelper;
#Qualifier("myUserDetails")
#Autowired
private UserDetailsService userDetailsService;
String jwtToken;
private final UserService userService;
#Autowired
LoginController(UserService userService){
this.userService = userService;
}
#PostMapping(value = "/register",consumes = "application/json")
public ResponseEntity<?> register(#RequestBody RegistrationDTO registrationDTO) throws InvalidKeySpecException, NoSuchAlgorithmException {
return this.login(new AuthenticationDTO(registrationDTO.getEmail(), registrationDTO.getPassword()));
}
#PostMapping(value = "/login",consumes = "application/json")
public ResponseEntity<?> login(#RequestBody AuthenticationDTO authenticationDTO) throws InvalidKeySpecException, NoSuchAlgorithmException {
System.out.print("\n" + authenticationDTO.getEmail() + " " + authenticationDTO.getPassword() + "\n");
final Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
authenticationDTO.getEmail(), authenticationDTO.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails=(UserDetails) authentication.getPrincipal();
String jwtToken=jWTTokenHelper.generateToken(userDetails.getUsername());
this.jwtToken = jwtToken;
LoginResponseDTO responseDTO = new LoginResponseDTO(jwtToken);
//try to find out if it's a customer or not
return ResponseEntity.ok(responseDTO);
}
#GetMapping("/userinfo")
#ResponseBody
public ResponseEntity<?> getUserInfo(Principal user){
User userObj = (User)userDetailsService.loadUserByUsername(user.getName());
UserDTO userInfo = new UserDTO(userObj.getId(),userObj.getName(),userObj.getEmail(),userObj.getAuthorities().toArray());
return ResponseEntity.ok(userInfo);
}
}
Login Controller Test
import com.example.demo.Controller.LoginController;
import com.example.demo.Model.DTOs.AuthenticationDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
#AutoConfigureMockMvc
#RunWith(MockitoJUnitRunner.class)
public class LoginControllerTest {
#Autowired
private MockMvc mockMvc;
#InjectMocks
private LoginController loginController;
#Before
public void setUp(){
mockMvc = MockMvcBuilders.standaloneSetup(loginController).build();
}
#Test
public void testLogin() throws Exception{
AuthenticationDTO authenticationDTO = new AuthenticationDTO("ztudorita#gmail.com","Shaorma72.");
mockMvc.perform(
MockMvcRequestBuilders
.post("/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(authenticationDTO))
// .accept(MediaType.APPLICATION_JSON)
)
.andReturn();
}
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
ERROR CONSOLE
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
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:199)
at com.example.demo.ControllerTest.LoginControllerTest.testLogin(LoginControllerTest.java:38)
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:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:55)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:100)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:107)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:41)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: java.lang.NullPointerException
at com.example.demo.Controller.LoginController.login(LoginController.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at

java.lang.IllegalStateException: Failed to execute - CommandLineRunner NullPointer Excaption

Repository
package com.example.demo.jpa;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.example.demo.entity.Person;
#Repository
#Transactional
public class RepositoryJpa {
#PersistenceContext
EntityManager entityManager;
//#Autowired
Person person = new Person();
public Person findById(int id) {
System.out.println("value of parameter id is "+id);
return entityManager.find(Person.class,id);
}
public Person update(Person person) {
return entityManager.merge(person);
}
}
Entity table:
package com.example.demo.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
//#Table(name="person")
public class Person {
#Id
private int id;
private String name;
private String location;
private String birth_date;
// public Person(int i, String string, String string2, String string3) {}
public Person(int id, String name, String location, String birth_date) {
// super();
this.id = id;
this.name = name;
this.location = location;
this.birth_date = birth_date;
}
public Person(String name, String location, String birth_date) {
// super();
this.name = name;
this.location = location;
this.birth_date = birth_date;
}
public Person() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
System.out.println("i called setID=" + this.id);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
System.out.println("i called setName=" + this.name);
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
System.out.println("i called setLocation=" + this.location);
}
public String getBirth_date() {
return birth_date;
}
public void setBirth_date(String birth_date) {
this.birth_date = birth_date;
// System.out.println("i called setBirth_ID="+this.birth_date);
}
/*
* #Override public String toString() { return "Person [id=" + id + ", name=" +
* name + ", location=" + location + ", birth_date=" + birth_date + ", getId()="
* + getId() + ", getName()=" + getName() + ", getLocation()=" + getLocation() +
* ", getBirth_date()=" + getBirth_date() + "]"; }
*/
}
SpringBootApplication
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import com.example.demo.entity.Person;
import com.example.demo.jpa.RepositoryJpa;
#SpringBootApplication
public class JpaDemoApplication implements CommandLineRunner {
private Logger logger=LoggerFactory.getLogger(this.getClass());
//#Autowired
Person person = new Person();
RepositoryJpa repo = new RepositoryJpa();
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(JpaDemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("hello all");
logger.info("find by id -> {}", repo.findById(2));
logger.info("insert user-> {}",repo.update(new Person(5,"gaurav","chicago","05/06/82")));
}
}
Application Properties
spring.h2.console.enabled=true
#spring.datasource.url=jdbc:h2:mem:testdb
#spring.batch.job.enabled=false
spring.jpa.show-sql=true
##EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
spring.jpa.defer-datasource-initialization=true
I'm a beginner to SpringBoot and I don't know what wrong I'm doing related to entity manager method it giving the error of and also #Autowired not working, I'm manually creating the object!
Help me please!!!
Console error screenshot also shared below please check:
Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:780) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:761) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:310) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.4.jar:2.6.4]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.4.jar:2.6.4]
at com.example.demo.JpaDemoApplication.main(JpaDemoApplication.java:31) ~[classes/:na]
Caused by: java.lang.NullPointerException: null
at com.example.demo.jpa.RepositoryJpa.update(RepositoryJpa.java:31) ~[classes/:na]
at com.example.demo.JpaDemoApplication.run(JpaDemoApplication.java:46) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:777) ~[spring-boot-2.6.4.jar:2.6.4]
... 5 common frames omitted
console
You should Autowire the repository bean in JpaDemoApplication class, you should never create an object for spring component using new keyword
#SpringBootApplication
public class JpaDemoApplication implements CommandLineRunner {
private Logger logger=LoggerFactory.getLogger(this.getClass());
#Autowired
RepositoryJpa repositoryJpa;
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(JpaDemoApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("hello all");
logger.info("find by id -> {}", repo.findById(2));
logger.info("insert user-> {}",repo.update(new Person(5,"gaurav","chicago","05/06/82")));
}
}

Spring CRUD App: Servlet.service() for servlet [dispatcherServlet] : java.lang.NullPointerException]

I've a problem to get employees data from mySQL db. According to logs there is a problem at line: 36 in my EmployeeServiceImpl.listEmployess metod.
Logs:
2018-10-18 16:07:42.871 ERROR 1504 --- [nio-8090-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
at com.project.service.EmployeeServiceImpl.listEmployess(EmployeeServiceImpl.java:36) ~[classes/:na]
com.project.service.EmployeeServiceImpl$$FastClassBySpringCGLIB$$c7d76ecc.invoke() ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) ~[spring-tx-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688) ~[spring-aop-5.0.9.RELEASE.jar:5.0.9.RELEASE]
at com.project.service.EmployeeServiceImpl$$EnhancerBySpringCGLIB$$1390ca06.listEmployess() ~[classes/:na]
at com.project.controller.EmployeeController.listEmployess(EmployeeController.java:34) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
EmployeeServiceImpl:
package com.project.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.project.dao.EmployeeDAO;
import com.project.entity.TEmployee;
#Service("employeeService")
public class EmployeeServiceImpl implements EmployeeService {
private EmployeeDAO employeeDAO;
public void setEmployeeDAO(EmployeeDAO employeeDAO) {
this.employeeDAO = employeeDAO;
}
#Override
#Transactional
public void addEmployee(TEmployee p) {
this.employeeDAO.addEmployee(p);
}
#Override
#Transactional
public void updateEmployee(TEmployee p) {
this.employeeDAO.updateEmployee(p);
}
#Override
#Transactional
public List<TEmployee> listEmployess() {
return this.employeeDAO.listEmployess();
}
#Override
#Transactional
public TEmployee getEmployeeById(int employee_id) {
return this.employeeDAO.getEmployeeById(employee_id);
}
#Override
#Transactional
public void removeEmployee(int employee_id) {
this.employeeDAO.removeEmployee(employee_id);
}
}
EmployeeService:
package com.project.service;
import java.util.List;
import org.springframework.context.annotation.ComponentScan;
import com.project.entity.TEmployee;
#ComponentScan(basePackages= {"com.project.*"})
public interface EmployeeService {
public void addEmployee(TEmployee p);
public void updateEmployee(TEmployee p);
public List<TEmployee> listEmployess();
public TEmployee getEmployeeById(int id);
public void removeEmployee(int id);
}
EmployeeDAO:
package com.project.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import com.project.entity.TEmployee;
#ComponentScan(basePackages= {"com.project.*"})
public interface EmployeeDAO {
public void addEmployee(TEmployee p);
public void updateEmployee(TEmployee p);
public List<TEmployee> listEmployess();
public TEmployee getEmployeeById(int employee_id);
public void removeEmployee(int employee_id);
}
EmployeeDAOImpl:
package com.project.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.project.entity.TEmployee;
#Repository
public class EmployeeDAOImpl implements EmployeeDAO {
private static final Logger logger = LoggerFactory.getLogger(EmployeeDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void addEmployee(TEmployee p) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(p);
logger.info("TEmployee saved successfully, TEmployee Details="+p);
}
#Override
public void updateEmployee(TEmployee p) {
Session session = this.sessionFactory.getCurrentSession();
session.update(p);
logger.info("TEmployee updated successfully, TEmployee Details="+p);
}
#SuppressWarnings("unchecked")
#Override
public List<TEmployee> listEmployess() {
Session session = this.sessionFactory.getCurrentSession();
List<TEmployee> EmployessList = session.createQuery("from TEmployee").list();
for(TEmployee p : EmployessList){
logger.info("TEmployee List::"+p);
}
return EmployessList;
}
#Override
public TEmployee getEmployeeById(int employee_id) {
Session session = this.sessionFactory.getCurrentSession();
TEmployee p = (TEmployee) session.load(TEmployee.class, new Integer(employee_id));
logger.info("TEmployee loaded successfully, TEmployee details="+p);
return p;
}
#Override
public void removeEmployee(int employee_id) {
Session session = this.sessionFactory.getCurrentSession();
TEmployee p = (TEmployee) session.load(TEmployee.class, new Integer(employee_id));
if(null != p){
session.delete(p);
}
logger.info("TEmployee deleted successfully, TEmployee details="+p);
}
}
And EmployeeController:
package com.project.controller;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.project.entity.TEmployee;
import com.project.service.EmployeeService;
#ComponentScan(basePackages= {"com.project.*"})
#Controller
public class EmployeeController {
#Resource(name = "employeeService")
private EmployeeService employeeService;
#Autowired(required=true)
#Qualifier(value="employeeService")
public void setEmployeeService(EmployeeService ps){
this.employeeService = ps;
}
#RequestMapping(value = "/employess", method = RequestMethod.GET)
public String listEmployess(Model model) {
model.addAttribute("employee", new TEmployee());
model.addAttribute("listEmployess", this.employeeService.listEmployess());
return "employee";
}
//For add and update person both
#RequestMapping(value= "/employee/add", method = RequestMethod.POST)
public String addEmployee(#ModelAttribute("employee") TEmployee p){
if(p.getEmployeeID() == 0){
//new person, add it
this.employeeService.addEmployee(p);
}else{
//existing person, call update
this.employeeService.updateEmployee(p);
}
return "redirect:/employess";
}
#RequestMapping("/remove/{employee_id}")
public String removeEmployee(#PathVariable("employee_id") int employee_id){
this.employeeService.removeEmployee(employee_id);
return "redirect:/employess";
}
#RequestMapping("/edit/{employee_id}")
public String editEmployee(#PathVariable("employee_id") int employee_id, Model model){
model.addAttribute("employee", this.employeeService.getEmployeeById(employee_id));
model.addAttribute("listEmployess", this.employeeService.listEmployess());
return "employee";
}
}
So, according to logs there is a NPE returning from this line:
return this.employeeDAO.listEmployess();
Do you have any idea what could be wrong here?
Thanks in advance!
Hi instead of setter method use Autowired annotation on dependency private EmployeeDAO employeeDAO;
like
#Autowired
private EmployeeDAO employeeDAO;

How to testing Spring validator with Junit and Mockito

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") );
}

Resources