Spring MockMvc Test : NullPointerException for mvc.perform() The Next CEO of Stack OverflowHow do you assert that a certain exception is thrown in JUnit 4 tests?Junit test case for spring MVC with RestEasyMock MVC unexpected resultMocking a file, filewriter and csvwriter within a method for unit test throwing NullPointerExceptionSpring MVC application Junit test case failingMappingException: Invalid path reference club.name! Associations can only be pointed to directly or via their id propertyspring boot hystrix integrationUnit testing code in catch block of a Spring Controllermapstruct junit test NullPointerExceptionJUnit forRest API with File Uploader fails with 406 Error

Why did we only see the N-1 starfighters in one film?

How do spells that require an ability check vs. the caster's spell save DC work?

Was a professor correct to chastise me for writing "Prof. X" rather than "Professor X"?

If the heap is initialized for security, then why is the stack uninitialized?

How to write papers efficiently when English isn't my first language?

Inappropriate reference requests from Journal reviewers

Why didn't Theresa May consult with Parliament before negotiating a deal with the EU?

Customer Requests (Sometimes) Drive Me Bonkers!

Anatomically Correct Mesopelagic Aves

Increase performance creating Mandelbrot set in python

Visit to the USA with ESTA approved before trip to Iran

Can a caster that cast Polymorph on themselves stop concentrating at any point even if their Int is low?

What is the purpose of the Evocation wizard's Potent Cantrip feature?

Term for the "extreme-extension" version of a straw man fallacy?

How long to clear the 'suck zone' of a turbofan after start is initiated?

Is a stroke of luck acceptable after a series of unfavorable events?

How can I get through very long and very dry, but also very useful technical documents when learning a new tool?

Would this house-rule that treats advantage as a +1 to the roll instead (and disadvantage as -1) and allows them to stack be balanced?

How to make a variable always equal to the result of some calculations?

Where to find order of arguments for default functions

How should I support this large drywall patch?

What happens if you roll doubles 3 times then land on "Go to jail?"

What is the difference between "behavior" and "behaviour"?

What can we do to stop prior company from asking us questions?



Spring MockMvc Test : NullPointerException for mvc.perform()



The Next CEO of Stack OverflowHow do you assert that a certain exception is thrown in JUnit 4 tests?Junit test case for spring MVC with RestEasyMock MVC unexpected resultMocking a file, filewriter and csvwriter within a method for unit test throwing NullPointerExceptionSpring MVC application Junit test case failingMappingException: Invalid path reference club.name! Associations can only be pointed to directly or via their id propertyspring boot hystrix integrationUnit testing code in catch block of a Spring Controllermapstruct junit test NullPointerExceptionJUnit forRest API with File Uploader fails with 406 Error










0















I am new to unit test in spring Boot. I am trying to run a simple test of the controller.
But i'am getting a NullPointerException.



here is my code :



The controller class:



@RequestMapping("/trainings")
public class TrainingController

@Autowired
TrainingService ts;

@PostMapping()
public JsonResponse<AllTrainings> getTrainings()
JsonResponse<AllTrainings> json = new JsonResponse<AllTrainings>();
json.setStatus(JsonResponse.Status.OK);
json.setData(new AllTrainings(ts.getTrainings()));
return json;



The TrainingTest :



@RunWith(SpringRunner.class)
public abstract class TrainingTest

protected MockMvc mvc;
protected ObjectMapper mapper = new ObjectMapper();

@Before
public void setup()
MockitoAnnotations.initMocks(this);


@Test
public abstract void testGetTrainings() throws Exception;

@Test
public abstract void testGetTrainingById() throws Exception;

protected String toJson(Object object) throws JsonProcessingException
return mapper.writeValueAsString(object);




The TrainingControllerTest :



public class TrainingControllerTest extends TrainingTest{
@InjectMocks protected TrainingController controller;

@MockBean
TrainingRepository trainingRepo;

@Before
public void setup()
super.setup();
mvc = MockMvcBuilders.standaloneSetup(this.controller).build();


@Override
public void testGetTrainings() throws Exception
Training ang = new Training("TR0004");

Mockito
.when(this.trainingRepo.findAll())
.thenReturn(Arrays.asList(ang));

mvc.perform(MockMvcRequestBuilders.get("/trainings")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk());



And here the error i'am getting:



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.doPost(FrameworkServlet.java:908)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
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:182)
at fr.ter.forco.training.TrainingControllerTest.testGetTrainings(TrainingControllerTest.java:41)
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.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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.lang.NullPointerException
at fr.ter.forco.controllers.TrainingController.getTrainings(TrainingController.java:38)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
... 41 more


The exception appears in the mvc.perform!
I really don't know why i'am getting this error.



Thank you.










share|improve this question
























  • What’s the complete stack trace of the failure?

    – Andy Wilkinson
    Mar 8 at 20:38











  • @AndyWilkinson i changed it with the complete stack trace

    – MongJi
    Mar 8 at 20:56






  • 1





    I would guess that ts in your controller is null. What are you expecting to have set it for you?

    – Andy Wilkinson
    Mar 8 at 21:52















0















I am new to unit test in spring Boot. I am trying to run a simple test of the controller.
But i'am getting a NullPointerException.



here is my code :



The controller class:



@RequestMapping("/trainings")
public class TrainingController

@Autowired
TrainingService ts;

@PostMapping()
public JsonResponse<AllTrainings> getTrainings()
JsonResponse<AllTrainings> json = new JsonResponse<AllTrainings>();
json.setStatus(JsonResponse.Status.OK);
json.setData(new AllTrainings(ts.getTrainings()));
return json;



The TrainingTest :



@RunWith(SpringRunner.class)
public abstract class TrainingTest

protected MockMvc mvc;
protected ObjectMapper mapper = new ObjectMapper();

@Before
public void setup()
MockitoAnnotations.initMocks(this);


@Test
public abstract void testGetTrainings() throws Exception;

@Test
public abstract void testGetTrainingById() throws Exception;

protected String toJson(Object object) throws JsonProcessingException
return mapper.writeValueAsString(object);




The TrainingControllerTest :



public class TrainingControllerTest extends TrainingTest{
@InjectMocks protected TrainingController controller;

@MockBean
TrainingRepository trainingRepo;

@Before
public void setup()
super.setup();
mvc = MockMvcBuilders.standaloneSetup(this.controller).build();


@Override
public void testGetTrainings() throws Exception
Training ang = new Training("TR0004");

Mockito
.when(this.trainingRepo.findAll())
.thenReturn(Arrays.asList(ang));

mvc.perform(MockMvcRequestBuilders.get("/trainings")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk());



And here the error i'am getting:



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.doPost(FrameworkServlet.java:908)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
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:182)
at fr.ter.forco.training.TrainingControllerTest.testGetTrainings(TrainingControllerTest.java:41)
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.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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.lang.NullPointerException
at fr.ter.forco.controllers.TrainingController.getTrainings(TrainingController.java:38)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
... 41 more


The exception appears in the mvc.perform!
I really don't know why i'am getting this error.



Thank you.










share|improve this question
























  • What’s the complete stack trace of the failure?

    – Andy Wilkinson
    Mar 8 at 20:38











  • @AndyWilkinson i changed it with the complete stack trace

    – MongJi
    Mar 8 at 20:56






  • 1





    I would guess that ts in your controller is null. What are you expecting to have set it for you?

    – Andy Wilkinson
    Mar 8 at 21:52













0












0








0


1






I am new to unit test in spring Boot. I am trying to run a simple test of the controller.
But i'am getting a NullPointerException.



here is my code :



The controller class:



@RequestMapping("/trainings")
public class TrainingController

@Autowired
TrainingService ts;

@PostMapping()
public JsonResponse<AllTrainings> getTrainings()
JsonResponse<AllTrainings> json = new JsonResponse<AllTrainings>();
json.setStatus(JsonResponse.Status.OK);
json.setData(new AllTrainings(ts.getTrainings()));
return json;



The TrainingTest :



@RunWith(SpringRunner.class)
public abstract class TrainingTest

protected MockMvc mvc;
protected ObjectMapper mapper = new ObjectMapper();

@Before
public void setup()
MockitoAnnotations.initMocks(this);


@Test
public abstract void testGetTrainings() throws Exception;

@Test
public abstract void testGetTrainingById() throws Exception;

protected String toJson(Object object) throws JsonProcessingException
return mapper.writeValueAsString(object);




The TrainingControllerTest :



public class TrainingControllerTest extends TrainingTest{
@InjectMocks protected TrainingController controller;

@MockBean
TrainingRepository trainingRepo;

@Before
public void setup()
super.setup();
mvc = MockMvcBuilders.standaloneSetup(this.controller).build();


@Override
public void testGetTrainings() throws Exception
Training ang = new Training("TR0004");

Mockito
.when(this.trainingRepo.findAll())
.thenReturn(Arrays.asList(ang));

mvc.perform(MockMvcRequestBuilders.get("/trainings")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk());



And here the error i'am getting:



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.doPost(FrameworkServlet.java:908)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
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:182)
at fr.ter.forco.training.TrainingControllerTest.testGetTrainings(TrainingControllerTest.java:41)
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.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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.lang.NullPointerException
at fr.ter.forco.controllers.TrainingController.getTrainings(TrainingController.java:38)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
... 41 more


The exception appears in the mvc.perform!
I really don't know why i'am getting this error.



Thank you.










share|improve this question
















I am new to unit test in spring Boot. I am trying to run a simple test of the controller.
But i'am getting a NullPointerException.



here is my code :



The controller class:



@RequestMapping("/trainings")
public class TrainingController

@Autowired
TrainingService ts;

@PostMapping()
public JsonResponse<AllTrainings> getTrainings()
JsonResponse<AllTrainings> json = new JsonResponse<AllTrainings>();
json.setStatus(JsonResponse.Status.OK);
json.setData(new AllTrainings(ts.getTrainings()));
return json;



The TrainingTest :



@RunWith(SpringRunner.class)
public abstract class TrainingTest

protected MockMvc mvc;
protected ObjectMapper mapper = new ObjectMapper();

@Before
public void setup()
MockitoAnnotations.initMocks(this);


@Test
public abstract void testGetTrainings() throws Exception;

@Test
public abstract void testGetTrainingById() throws Exception;

protected String toJson(Object object) throws JsonProcessingException
return mapper.writeValueAsString(object);




The TrainingControllerTest :



public class TrainingControllerTest extends TrainingTest{
@InjectMocks protected TrainingController controller;

@MockBean
TrainingRepository trainingRepo;

@Before
public void setup()
super.setup();
mvc = MockMvcBuilders.standaloneSetup(this.controller).build();


@Override
public void testGetTrainings() throws Exception
Training ang = new Training("TR0004");

Mockito
.when(this.trainingRepo.findAll())
.thenReturn(Arrays.asList(ang));

mvc.perform(MockMvcRequestBuilders.get("/trainings")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk());



And here the error i'am getting:



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.doPost(FrameworkServlet.java:908)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
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:182)
at fr.ter.forco.training.TrainingControllerTest.testGetTrainings(TrainingControllerTest.java:41)
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.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.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.lang.NullPointerException
at fr.ter.forco.controllers.TrainingController.getTrainings(TrainingController.java:38)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
... 41 more


The exception appears in the mvc.perform!
I really don't know why i'am getting this error.



Thank you.







java spring-boot testing junit






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 20:56







MongJi

















asked Mar 8 at 12:33









MongJiMongJi

305




305












  • What’s the complete stack trace of the failure?

    – Andy Wilkinson
    Mar 8 at 20:38











  • @AndyWilkinson i changed it with the complete stack trace

    – MongJi
    Mar 8 at 20:56






  • 1





    I would guess that ts in your controller is null. What are you expecting to have set it for you?

    – Andy Wilkinson
    Mar 8 at 21:52

















  • What’s the complete stack trace of the failure?

    – Andy Wilkinson
    Mar 8 at 20:38











  • @AndyWilkinson i changed it with the complete stack trace

    – MongJi
    Mar 8 at 20:56






  • 1





    I would guess that ts in your controller is null. What are you expecting to have set it for you?

    – Andy Wilkinson
    Mar 8 at 21:52
















What’s the complete stack trace of the failure?

– Andy Wilkinson
Mar 8 at 20:38





What’s the complete stack trace of the failure?

– Andy Wilkinson
Mar 8 at 20:38













@AndyWilkinson i changed it with the complete stack trace

– MongJi
Mar 8 at 20:56





@AndyWilkinson i changed it with the complete stack trace

– MongJi
Mar 8 at 20:56




1




1





I would guess that ts in your controller is null. What are you expecting to have set it for you?

– Andy Wilkinson
Mar 8 at 21:52





I would guess that ts in your controller is null. What are you expecting to have set it for you?

– Andy Wilkinson
Mar 8 at 21:52












1 Answer
1






active

oldest

votes


















0














I'm not sure why you're getting this error but maybe if you add the @AutoConfigureMockMvc above your test class it could work? I always add this annotation when making use of MockMvc.






share|improve this answer























  • No it didn't work..

    – MongJi
    Mar 8 at 13:49











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55063346%2fspring-mockmvc-test-nullpointerexception-for-mvc-perform%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














I'm not sure why you're getting this error but maybe if you add the @AutoConfigureMockMvc above your test class it could work? I always add this annotation when making use of MockMvc.






share|improve this answer























  • No it didn't work..

    – MongJi
    Mar 8 at 13:49















0














I'm not sure why you're getting this error but maybe if you add the @AutoConfigureMockMvc above your test class it could work? I always add this annotation when making use of MockMvc.






share|improve this answer























  • No it didn't work..

    – MongJi
    Mar 8 at 13:49













0












0








0







I'm not sure why you're getting this error but maybe if you add the @AutoConfigureMockMvc above your test class it could work? I always add this annotation when making use of MockMvc.






share|improve this answer













I'm not sure why you're getting this error but maybe if you add the @AutoConfigureMockMvc above your test class it could work? I always add this annotation when making use of MockMvc.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 8 at 12:48









Sige VVSige VV

337




337












  • No it didn't work..

    – MongJi
    Mar 8 at 13:49

















  • No it didn't work..

    – MongJi
    Mar 8 at 13:49
















No it didn't work..

– MongJi
Mar 8 at 13:49





No it didn't work..

– MongJi
Mar 8 at 13:49



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55063346%2fspring-mockmvc-test-nullpointerexception-for-mvc-perform%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived