Cant apply rest controllers junit tests correctly - java

I am trying to apply junit test for my rest controllers.
I've tried to apply junit 4 but I got 404 error instead 200.
It looks like something is not initialized but cant't figured what.
Here is tutorial I have tried to apply.
https://www.youtube.com/watch?v=8S8o46avgAw
I also tried some different tutorials with junit 5 but the result was the same.
Here you can find the whole project.
https://github.com/WojciechWeg/tiny-bank/tree/tests
Just before publishing this post I've applied the following:
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(customerController)
.build();
customer = new Customer("Jan","Kowalski",new Date(),"Marszalkowska",new ArrayList<>());
customerService.createNewCustomer(customer);
System.out.println("Customers from service: "+ customerService.getAllCustomers());
}
But the result of it is:
Customers from service: []
So it returns nothing. Above snippet is not in repo link.
Rest controller class:
package com.tinybank.tinybankapi.controllers;
import com.tinybank.tinybankapi.model.Account;
import com.tinybank.tinybankapi.model.Customer;
import com.tinybank.tinybankapi.model.CustomerResource;
import com.tinybank.tinybankapi.services.CustomerService;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resources;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
import java.util.List;
#RestController
#RequestMapping(CustomerController.BASE_URL)
public class CustomerController {
public static final String BASE_URL = "api/customers";
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
#GetMapping
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<Resources<List<Customer>>> getListOfCustomers() {
Resources<List<Customer>> resources = new Resources(customerService.getAllCustomers());
String uri = ServletUriComponentsBuilder.fromCurrentRequest().build().toUriString();
resources.add(new Link(uri,"self"));
return ResponseEntity.ok(resources);
}
#GetMapping({"/{id}"})
#ResponseStatus(HttpStatus.OK)
public Customer getCustomer(#PathVariable Long id) {
return customerService.getCustomerById(id);
}
#DeleteMapping({"/{id}"})
#ResponseStatus(HttpStatus.OK)
public void deleteCustomer(#PathVariable Long id) {
customerService.deleteCustomerById(id);
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<CustomerResource> createNewCustomer(#RequestBody #Valid Customer Customer) {
Customer customer = customerService.createNewCustomer(Customer);
URI uri = MvcUriComponentsBuilder.fromController(getClass())
.path("/{id}")
.buildAndExpand(customer.getId())
.toUri();
return ResponseEntity.created(uri).body(new CustomerResource(customer));
}
#PutMapping({"/{id}/open_account"})
#ResponseStatus(HttpStatus.OK)
public void openAccount(#PathVariable Long id, #RequestBody Account account) {
customerService.openAccount(id, account);
}
}
Test class:
package com.tinybank.tinybankapi.controllers;
import com.tinybank.tinybankapi.model.Customer;
import com.tinybank.tinybankapi.services.CustomerService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.Date;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(SpringJUnit4ClassRunner.class)
public class CustomerControllerTest {
private MockMvc mockMvc;
#Mock
private CustomerService customerService;
#InjectMocks
private CustomerController customerController;
Customer customer;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(customerController)
.build();
customer = new Customer("Jan","Kowalski",new Date(),"Marszalkowska",new ArrayList<>());
customerService.createNewCustomer(customer);
System.out.println("Customers from service: "+ customerService.getAllCustomers());
}
#Test
public void getCustomer() throws Exception {
when(customerService.getCustomerById(any())).thenReturn(customer);
mockMvc.perform(get("api/customers/1"))
.andExpect(status().isOk());
}
}
This is how stack trace looks like:
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
at com.tinybank.tinybankapi.controllers.CustomerControllerTest.getCustomer(CustomerControllerTest.java:53)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
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:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Have you tried below approach without injecting mocks?
MockMvcBuilders.standaloneSetup(new CustomerController())
.build();
EDIT:
I've ran your code locally.
Do this:
mockMvc = MockMvcBuilders.standaloneSetup(new CustomerController(customerService))
.build();
And add slash to the beginning of URL
mockMvc.perform(get("/api/customers/1"))
.andExpect(status().isOk());

Related

spring boot Rest : NullPointerException error

I'm developing a Spring boot web application. and I'm working on spring boot to test the rest api to get hospital list, but i'am getting the following exception every time
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:166)
at com.bezkoder.springjwt.Controller.HospitalControllerTest.testgetAllHospitals(HospitalControllerTest.java:134)
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.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.DefaultInternalRunner$1.run(DefaultInternalRunner.java:78)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:84)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:161)
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:221)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.lang.NullPointerException
at com.bezkoder.springjwt.controllers.HospitalController.getAllHospitals(HospitalController.java:64)
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:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
... 36 more
this is my test
package com.bezkoder.springjwt.Controller;
import com.bezkoder.springjwt.controllers.HospitalController;
import com.bezkoder.springjwt.models.Hospital;
import com.bezkoder.springjwt.repository.HospitalRepository;
import com.bezkoder.springjwt.services.HospitalService;
import com.fasterxml.jackson.core.JsonProcessingException;
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.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
#RunWith(MockitoJUnitRunner.class)
public class HospitalControllerTest {
#Mock
private HospitalService hospitalService;
#Mock
private HospitalRepository hospitalRepository;
#InjectMocks
private HospitalController hospitalController;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(hospitalController).build();
}
private MockMvc mockMvc;
private String mapToJson(Object object) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(object);
}
#Test
public void testcreateHospital() throws Exception {
Hospital hospital = new Hospital();
hospital.setId((long) 1);
hospital.setName("appellib");
hospital.setAdministrativeAddress("ad1234");
hospital.setFinessNumber(123456);
hospital.setSiretNumber(123456);
String uri = "/api/auth/hospital/add";
// String inputInJson = this.mapToJson(hospital);
String inputInJson = this.mapToJson(hospital);
// MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post(uri)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(inputInJson)).andReturn();
int status = mvcResult.getResponse().getStatus();
assertEquals(200, status);
String content = mvcResult.getResponse().getContentAsString();
assertEquals(content, "Hospital is created successfully");
}
#Test
public void testgetAllHospitals() throws Exception{
String uri = "/api/auth/hospital/display";
Hospital hospital = new Hospital();
hospital.setId((long) 1);
hospital.setName("appellib");
hospital.setAdministrativeAddress("ad1234");
hospital.setFinessNumber(123456);
hospital.setSiretNumber(123456);
Hospital hospital1 = new Hospital();
hospital1.setId((long) 2);
hospital1.setName("Aled");
hospital1.setAdministrativeAddress("ad4567");
hospital1.setFinessNumber(98765);
hospital1.setSiretNumber(1256767);
List<Hospital> hospitalsList = new ArrayList<>();
hospitalsList.add(hospital);
hospitalsList.add(hospital1);
Mockito.when(hospitalService.findAll()).thenReturn(hospitalsList);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
String expectedJson = this.mapToJson(hospitalsList);
String outputInJson = result.getResponse().getContentAsString();
MockHttpServletResponse response = result.getResponse();
assertThat(outputInJson, is(equalTo(expectedJson)));
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
}
and this is the function i'm testing
package com.bezkoder.springjwt.controllers;
import com.bezkoder.springjwt.models.Hospital;
import com.bezkoder.springjwt.payload.response.MessageResponse;
import com.bezkoder.springjwt.repository.HospitalRepository;
import com.bezkoder.springjwt.services.HospitalServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.logging.Logger;
#Controller
#RequestMapping("/api/auth/hospital")
public class HospitalController {
Logger logger = Logger.getLogger("com.Appel.lib.Controller.HospitalController");
#Autowired
HospitalServiceImpl hospitalService;
#Autowired
HospitalRepository hospitalRepository;
#PostMapping("/add")
public ResponseEntity<?> createHospital(#RequestBody Hospital hospital){
if (hospitalService.existsByName(hospital.getName())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: name is already taken!"));
}
if (hospitalService.existsByAdministrativeAddress(hospital.getAdministrativeAddress())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: administrative_address is already in use!"));
}
if (hospitalService.existsByFinessNumber(hospital.getFinessNumber())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: finess_number is already taken!"));
}
if (hospitalService.existsBySiretNumber(hospital.getSiretNumber())) {
return ResponseEntity
.badRequest()
.body(new MessageResponse("Error: siret_number is already in use!"));
}
hospitalService.add(hospital);
return ResponseEntity.ok(new MessageResponse("Hospital registered successfully!"));
}
#GetMapping("/display")
public ResponseEntity<List<Hospital>> getAllHospitals() {
logger.info("Getting all Hospitals from hospital table...Call getAllHospitals ");
List<Hospital> hospitals = hospitalService.findAll();
logger.info("Data extracted from hospital table...");
return ResponseEntity.ok(hospitals) ;
}
}
i searched stackoverflow for any solution to a similar error, but i didn't find any, any solution suggested to fix this ?
Instead of :
return ResponseEntity.ok(hospitals) ;
Try this :
return ResponseEntity<List<hospitals>>(hospitals);
at com.bezkoder.springjwt.controllers.HospitalController.getAllHospitals(HospitalController.java:64)
check the object at line 64 it return null

ArrayIndexOutOfBoundsException when accessing the getter on an object created by Spring's class converter

I'm converting one object to another object, but when I try to use the getter on the object that was created, I'm getting an ArrayIndexOutOfBoundsException.
The data is a simple String in the field and is on a very straight-forward object.
I've gotten this same issue with both Spring Boot 2.1.1 & 2.1.7.
Note: To replicate the issue, I have to run using mvn test, mvn install, or use Eclipse' code coverage tool. Using Eclipse's Run or Debug utils succeeds without error.
Exception:
[ERROR] storeWithEncryption(com.forms.service.SpringConversionServiceTest) Time elapsed: 0.003 s <<< ERROR!
java.lang.ArrayIndexOutOfBoundsException: 1
at com.forms.service.SpringConversionServiceTest$To.<init>(SpringConversionServiceTest.java:45)
at com.forms.service.SpringConversionServiceTest.storeWithEncryption(SpringConversionServiceTest.java:26)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
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:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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:190)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:273)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:159)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:384)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:345)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:126)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:418)
Test Class
package com.forms.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.convert.ConversionService;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import com.forms.Application;
#RunWith(SpringRunner.class)
#ActiveProfiles("test")
#SpringBootTest(classes = { Application.class })
public class SpringConversionServiceTest {
#Autowired
private ConversionService conversionService;
#Test
public void storeWithEncryption() throws Exception {
From from = new From();
from.bob = "nope";
from.bob2 = "yep";
new To(conversionService.convert(from, To.class));
}
public static final class From {
String bob;
String bob2;
}
public static final class To {
public To() {
// TODO Auto-generated constructor stub
}
public To(To convert) {
this.bob = convert.bob;
this.bob2 = convert.bob2;
}
String bob;
String bob2;
}
}
FromToConverter
package com.forms.service;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import com.forms.service.SpringConversionServiceTest.From;
import com.forms.service.SpringConversionServiceTest.To;
import com.forms.service.converter.AbstractReflectionConverter;
#Component
public class FromToConverter extends AbstractReflectionConverter implements Converter<From, To> {
public To convert(From from) {
To to = new To();
try {
// 1 to 1 conversions
conversionByReflection(from, to);
} catch (IllegalAccessException e) {
throw new IllegalArgumentException("The source external Header cannot be converted into an internal Header", e);
}
return to;
}
}
Application.java
package com.forms;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
#SpringBootApplication
#ImportResource({ "classpath:spring/camel-context.xml" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Pom:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version>
</parent>
In order to get around this issue, I had to change from using spring's reflective ConversionService methods to just manually plugging in the values in the converter.
I won't be marking this as the solution as it doesn't really fix the issue if you need to use reflection, but I'm putting it here to serve as a work-around.

MockMVC Test reports does not declare any static, non-private, non-final, inner classes annotated with #Configuration

I am trying to call my ajax method via a Junit test case. I have referred to a truck load of SO questions to get to this point. But still I am getting
TestMockMVC does not declare any static, non-private, non-fin
al, inner classes annotated with #Configuration.
My AJAX call is
#RequestMapping(value = { "/saveEntityAjax", "/modifyEntityAjax" }, method = RequestMethod.POST)
public #ResponseBody String saveOrUpdateEntityAjax(
#RequestParam(value = "id") String id,
#RequestParam(value = "number") String number, HttpServletRequest httpServletRequest) {
My Junit Test case is
package test.controllers;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.AnnotationConfigWebContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.mnox.database.pojo.wrapper.v2.VehicleMasterPojoWrapper.VehiclePurpose;
#Configuration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader=AnnotationConfigWebContextLoader.class)
#WebAppConfiguration
public class TestMockMVC {
#Autowired
private WebApplicationContext context;
private MockMvc mvc;
#Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
}
#Test
public void test1CreateClient() {
SaveOrUpdateVehicleAjaxRequest vehicle = new SaveOrUpdateVehicleAjaxRequest("123", "KA-02-1234", 12,
VehiclePurpose.MAIN_VEHICLE.name(), "some alias");
try {
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post("/saveVehicleAjaxMethod")
.contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andReturn();
mvcResult.getModelAndView();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class SaveOrUpdateEntityAjaxRequest {
private String id;
private String number;
public SaveOrUpdateEntityAjaxRequest(String id, String number) {
super();
this.id = id;
this.number = number;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
}
I am getting the following errors
INFO : org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [test.controllers.TestMockMVC]: TestMockMVC does not declare any static, non-private, non-final, inner classes annotated with #Configuration.
INFO : org.springframework.test.context.web.WebTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
INFO : org.springframework.test.context.web.WebTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener#7f3b84b8, org.springframework.test.context.support.DependencyInjectionTestExecutionListener#57a3af25, org.springframework.test.context.support.DirtiesContextTestExecutionListener#2b662a77, org.springframework.test.context.transaction.TransactionalTestExecutionListener#7f0eb4b4, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener#5c33f1a9, org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener#1623b78d, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener#c8c12ac, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener#6adbc9d]
INFO : org.springframework.web.context.support.GenericWebApplicationContext - Refreshing org.springframework.web.context.support.GenericWebApplicationContext#3eb25e1a: startup date [Mon Sep 11 13:11:05 IST 2017]; root of context hierarchy
INFO : org.springframework.web.context.support.GenericWebApplicationContext - Closing org.springframework.web.context.support.GenericWebApplicationContext#3eb25e1a: startup date [Mon Sep 11 13:11:05 IST 2017]; root of context hierarchy
Edit : Jar's I am using are
spring-boot-test-1.4.0.RELEASE.jar
spring-security-test-4.0.0.RELEASE.jar
spring-context-3.1.0.RELEASE.jar
spring-test-4.1.9.RELEASE.jar
spring-core-3.1.0.RELEASE.jar
spring-web-3.1.0.RELEASE.jar
spring-expression-3.1.0.RELEASE.jar
spring-webmvc-3.1.0.RELEASE.jar
Edit : My folder structure is
src/main/java/test/controllers/TestMockMVC.java
src/main/webapp/WEB-INF/web.xml
src/main/webapp/WEB-INF/spring/root-context.xml
src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml
Edit :
I have a partial answer. I have modified my code to solve the issue reported in this question. Although I am stuck at a different point, I am answering the question partially.
CHANGE 1
#Configuration
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({
// "file:src/main/webapp/WEB-INF/web.xml"
"file:src/main/webapp/WEB-INF/spring/root-context.xml",
"file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml" })
#WebAppConfiguration
public class TestMockMVC {
#Autowired
FilterChainProxy springSecurityFilterChain;
#Autowired
private WebApplicationContext context;
private MockMvc mvc;
#Before
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context)
.apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain)).build();
}
#Test
public void test1CreateClient() {
SaveOrUpdateEntityAjaxRequest vehicle = new SaveOrUpdateEntityAjaxRequest("123", "KA-02-1234");
MvcResult mvcResult = null;
try {
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.post("/saveEntityAjaxMethod")
.content(new Gson().toJson(vehicle).getBytes()).contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
mvcResult = mvc.perform(request).andReturn();
mvcResult.getModelAndView();
} catch (Exception e) {
e.printStackTrace();
}
}
CHANGE 2
In my servlet-context.xml I added the following lines.
<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
<!-- properties -->
</bean>
Exception I am getting now
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization started
INFO : org.springframework.test.web.servlet.TestDispatcherServlet - FrameworkServlet '': initialization completed in 67 ms
java.lang.NullPointerException
at org.springframework.security.web.FilterChainProxy.getFilters(FilterChainProxy.java:223)
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.util.MethodInvoker.invoke(MethodInvoker.java:269)
at org.springframework.test.util.ReflectionTestUtils.invokeMethod(ReflectionTestUtils.java:307)
at org.springframework.security.test.web.support.WebTestUtils.findFilter(WebTestUtils.java:118)
at org.springframework.security.test.web.support.WebTestUtils.getSecurityContextRepository(WebTestUtils.java:57)
at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$SecurityContextRequestPostProcessorSupport.save(SecurityMockMvcRequestPostProcessors.java:434)
at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$TestSecurityContextHolderPostProcessor.postProcessRequest(SecurityMockMvcRequestPostProcessors.java:511)
at org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.postProcessRequest(MockHttpServletRequestBuilder.java:686)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:137)
at test.controllers.TestMockMVC.test1CreateClient(TestMockMVC.java:61)
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:70)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
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:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
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:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

NullPointerException on running selenium script with JUnit

I am using pageObject Model for my selenium automation.
Consider following browser config class.
package BrowserConfig;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class crossBrowserConfiguration {
By logInPanel = By.xpath("//div[#id='logInPanelHeading']");
public static WebDriver driver = null;
WebDriverWait wait = new WebDriverWait(driver,30);
#Before
public void initBrowser(){
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("Website that contains Login Page");
wait.until(ExpectedConditions.visibilityOfElementLocated(logInPanel));
}
#After
public void closeBrowser(){
driver.quit();
}
}
I have a page object of Log in screen.
package PageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import BrowserConfig.crossBrowserConfiguration;
public class LoginScreen extends crossBrowserConfiguration {
WebDriverWait wait = new WebDriverWait(driver,30);
By userName = By.xpath("//input[#id='txtUsername']");
By password = By.xpath("//input[#id='txtPassword']");
By loginButton = By.xpath("//input[#id='btnLogin']");
By welcomeNote = By.xpath("//a[#id='welcome']");
By empListVerify = By.xpath("//div[#id='employee-information']/a");
public void logIN(String UserName, String Password){
driver.findElement(userName).sendKeys(UserName);
driver.findElement(password).sendKeys(Password);
driver.findElement(loginButton).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(welcomeNote));
//Employee List Verification
String empListBtnText = driver.findElement(empListVerify).getText();
System.out.println(empListBtnText);
}
}
And finally, I have the following test case script:
package TestCases;
import org.junit.Test;
import BrowserConfig.crossBrowserConfiguration;
import PageObjects.LoginScreen;
public class initiateBrows extends crossBrowserConfiguration{
LoginScreen Obj1 = new LoginScreen();
#Test
public void runThis() throws Exception{
Obj1.logIN("admin", "123456");
}
}
When I run my test as JUnit Test, it gives nullPointerException without running at all. Stack trace for the exception is:
java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:212)
at org.openqa.selenium.support.ui.FluentWait.<init>(FluentWait.java:102)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:71)
at org.openqa.selenium.support.ui.WebDriverWait.<init>(WebDriverWait.java:45)
at BrowserConfig.crossBrowserConfiguration.<init>(crossBrowserConfiguration.java:15)
at TestCases.initiateBrows.<init>(initiateBrows.java:8)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
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)
at BrowserConfig.crossBrowserConfiguration.<init>(crossBrowserConfiguration.java:15)
refers to WebDriverWait wait = new WebDriverWait(driver,30);
Any insight into why am I facing this exception?
The wait field is initialized when the an object of the class is created. This happens before JUnit calls the #Before method. Therefore the driver object is null. There are different ways of fixing the issue. One is making the driver object a simple field and initialize it immediately.
public class crossBrowserConfiguration {
By logInPanel = By.xpath("//div[#id='logInPanelHeading']");
public final WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver,30);
#Before
public void initBrowser(){
driver.manage().window().maximize();
driver.get("Website that contains Login Page");
wait.until(ExpectedConditions.visibilityOfElementLocated(logInPanel));
}
#After
public void closeBrowser(){
driver.quit();
}
}

Spring controller unit testing with spring-test-mvc is failing

I am learning unit testing of spring controller with EasyMock and Spring test framework. I have done a simple unit testing for my controller.
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.firstmav.domain.Employee;
import com.firstmav.service.EmployeeService;
#Controller
public class DataController {
#Autowired
EmployeeService employeeservice;
#RequestMapping("form")
public ModelAndView getform(#ModelAttribute Employee employee){
return new ModelAndView("form");
}
#RequestMapping("reguser")
public ModelAndView registeruser(#ModelAttribute Employee employee){
employeeservice.insertRow(employee);
return new ModelAndView("redirect:list");
}
#RequestMapping("list")
public ModelAndView getlist(){
List<Employee> employeelist = employeeservice.getList();
return new ModelAndView("list", "employeeList", employeelist);
}
#RequestMapping("delete")
public ModelAndView deleteitem(#RequestParam int id){
employeeservice.deleteRow(id);
return new ModelAndView("redirect:list");
}
#RequestMapping("edit")
public ModelAndView edititem(#ModelAttribute Employee employee, #RequestParam int id){
Employee employeeObject = employeeservice.getRowByID(id);
return new ModelAndView("edit", "employeeObject", employeeObject);
}
#RequestMapping("update")
public ModelAndView updaterow(#ModelAttribute Employee employee){
employeeservice.updateRow(employee);
return new ModelAndView("redirect:list");
}
}
and i have my failing test case here.
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.firstmav.controller.DataController;
public class DataControllerTest {
private MockMvc mockmvc;
#Before
public void setup(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
mockmvc = MockMvcBuilders.standaloneSetup(new DataController()).setViewResolvers(viewResolver).build();
}
#Test
public void main() throws Exception{
mockmvc.perform(get("/form")).andExpect(status().isOk()).andExpect(view().name("form"));
}
}
I have included the controller import in the test case but i always getting the noclassdeffound exception.
java.lang.NoClassDefFoundError: javax/servlet/ServletException
at org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup(MockMvcBuilders.java:71)
at com.ada.test.DataControllerTest.setup(DataControllerTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
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:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 25 more
I don't understand where i am making the mistake. Can any one help me or point me to right direction?
The issue is not related with your code.You're missing the library(jar) which contains javax.servlet.ServletException.So at runtime you're getting this exception.Check you class path if you have the servlet-api.jar in that location.
Though adding servlet-api.jar into your class path location should resolve the issue but if you want you can also check the jars that have this class here

Categories

Resources