Spring boot Autowired Service and Repository throwing nullpointerexceptionWhat's the difference between @Component, @Repository & @Service annotations in Spring?Mock MVC unexpected resultMocking a file, filewriter and csvwriter within a method for unit test throwing NullPointerExceptionMaven dependancy with spring boot and JunitMappingException: 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 Errorjava.lang.NoClassDefFoundError: with log4j velocity custom layout

Can an integer optimization problem be convex?

What benefits does the Power Word Kill spell have?

What exactly did this mechanic sabotage on the American Airlines 737, and how dangerous was it?

Strange Sticky Substance on Digital Camera

Hiking with a mule or two?

Is it impolite to ask for an in-flight catalogue with no intention of buying?

How can this Stack Exchange site have an animated favicon?

Could Apollo astronauts see city lights from the moon?

Are there any adverse impacts if I keep WiFi router on all time?

Is there any iPhone SE out there with 3D Touch?

What is the meaning of word 'crack' in chapter 33 of A Game of Thrones?

Can the U.S. president make military decisions without consulting anyone?

I reverse the source code, you negate the input!

If the EU does not offer an extension to UK's Article 50 invocation, is the Benn Bill irrelevant?

Cut a cake into 3 equal portions with only a knife

Replace HP Smart Array RAID Controller with newer generation controller (e.g. 410 -> 420)

Does wetting a beer glass change the foam characteristics?

What can a pilot do if an air traffic controller is incapacitated?

Late 1970's and 6502 chip facilities for operating systems

Where are they calling from?

Is it more effective to add yeast before or after kneading?

How to make interviewee comfortable interviewing in lounge chairs

Can a broken/split chain be reassembled?

How to manage expenditure when billing cycles and paycheck cycles are not aligned?



Spring boot Autowired Service and Repository throwing nullpointerexception


What's the difference between @Component, @Repository & @Service annotations in Spring?Mock MVC unexpected resultMocking a file, filewriter and csvwriter within a method for unit test throwing NullPointerExceptionMaven dependancy with spring boot and JunitMappingException: 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 Errorjava.lang.NoClassDefFoundError: with log4j velocity custom layout






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am testing a simple beginner spring boot application, but it keeps throwing NullPointerException for my service class and my repository class.

This is my controller class:



@EnableAutoConfiguration
@RestController
public class MyController

@Autowired
private MyService service;


@GetMapping("/welcome")
public String home throws IOException
return service.getEntities();





This is the Service class:



@EnableAutoConfiguration
@Service
public class MyService{

@Autowired(required=true)
private MyRepository repository;

public MyService()
;

public List<Entity> getEntities() throws IOException
return repository.findAll();



And this is the repository:



@Repository
public interface MyRepository extends JpaRepository<Entity, Long>

List<Entity> findAll();




So, if I run the application everything is ok. The problem is when I run this test:



@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyService.class, MyController.class, Entity.class )
@ComponentScan("test.firstproject")
@EntityScan(basePackages = "test.firstproject.entities")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@EnableJpaRepositories("test.firstproject.repository")
@EnableAutoConfiguration
public class TestController

private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController).build();

public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

@Autowired
private ObjectMapper objectMapper;


@Test
public void allEntities()
this.objectMapper = new ObjectMapper();
try
ResultActions resultActions = this.mvc
.perform(MockMvcRequestBuilders.get("/welcome").accept(MediaType.APPLICATION_JSON));
this.mvc.perform(get("/welcome")).andExpect(status().isOk());
MvcResult result = resultActions.andReturn();
List<Object> list = objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<Entity>>());
for (Object c : list)
assertTrue(c.getClass().equals(Entity.class));


catch (Exception e)
e.printStackTrace();






First, it threw NullPointerException when calling service.getEntities(). Then I've tried by initializing the service doing = new MyService(), but this time return repository.findAll(); throws the error. What's wrong?



EDIT - Stacktrace



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: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 com.example.demo.TestController.getAllEntities(TestController.java:58)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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.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 com.springmiddleware.controllers.MyController.allEntities(MyController.java:32)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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)
... 40 more









share|improve this question


























  • Please can you post the stack trace so we can see where the NPE comes from?

    – Not a JD
    Mar 28 at 16:51











  • @NotaJD added the stacktrace

    – MoM
    Mar 28 at 16:56











  • MockMvcBuilders.standaloneSetup(new MyController) is that valid?

    – Antoniossss
    Mar 28 at 16:57











  • What is "MyController.allEntities"? I see it in the stacktrace but not in the code

    – Not a JD
    Mar 28 at 17:00

















0















I am testing a simple beginner spring boot application, but it keeps throwing NullPointerException for my service class and my repository class.

This is my controller class:



@EnableAutoConfiguration
@RestController
public class MyController

@Autowired
private MyService service;


@GetMapping("/welcome")
public String home throws IOException
return service.getEntities();





This is the Service class:



@EnableAutoConfiguration
@Service
public class MyService{

@Autowired(required=true)
private MyRepository repository;

public MyService()
;

public List<Entity> getEntities() throws IOException
return repository.findAll();



And this is the repository:



@Repository
public interface MyRepository extends JpaRepository<Entity, Long>

List<Entity> findAll();




So, if I run the application everything is ok. The problem is when I run this test:



@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyService.class, MyController.class, Entity.class )
@ComponentScan("test.firstproject")
@EntityScan(basePackages = "test.firstproject.entities")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@EnableJpaRepositories("test.firstproject.repository")
@EnableAutoConfiguration
public class TestController

private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController).build();

public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

@Autowired
private ObjectMapper objectMapper;


@Test
public void allEntities()
this.objectMapper = new ObjectMapper();
try
ResultActions resultActions = this.mvc
.perform(MockMvcRequestBuilders.get("/welcome").accept(MediaType.APPLICATION_JSON));
this.mvc.perform(get("/welcome")).andExpect(status().isOk());
MvcResult result = resultActions.andReturn();
List<Object> list = objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<Entity>>());
for (Object c : list)
assertTrue(c.getClass().equals(Entity.class));


catch (Exception e)
e.printStackTrace();






First, it threw NullPointerException when calling service.getEntities(). Then I've tried by initializing the service doing = new MyService(), but this time return repository.findAll(); throws the error. What's wrong?



EDIT - Stacktrace



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: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 com.example.demo.TestController.getAllEntities(TestController.java:58)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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.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 com.springmiddleware.controllers.MyController.allEntities(MyController.java:32)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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)
... 40 more









share|improve this question


























  • Please can you post the stack trace so we can see where the NPE comes from?

    – Not a JD
    Mar 28 at 16:51











  • @NotaJD added the stacktrace

    – MoM
    Mar 28 at 16:56











  • MockMvcBuilders.standaloneSetup(new MyController) is that valid?

    – Antoniossss
    Mar 28 at 16:57











  • What is "MyController.allEntities"? I see it in the stacktrace but not in the code

    – Not a JD
    Mar 28 at 17:00













0












0








0








I am testing a simple beginner spring boot application, but it keeps throwing NullPointerException for my service class and my repository class.

This is my controller class:



@EnableAutoConfiguration
@RestController
public class MyController

@Autowired
private MyService service;


@GetMapping("/welcome")
public String home throws IOException
return service.getEntities();





This is the Service class:



@EnableAutoConfiguration
@Service
public class MyService{

@Autowired(required=true)
private MyRepository repository;

public MyService()
;

public List<Entity> getEntities() throws IOException
return repository.findAll();



And this is the repository:



@Repository
public interface MyRepository extends JpaRepository<Entity, Long>

List<Entity> findAll();




So, if I run the application everything is ok. The problem is when I run this test:



@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyService.class, MyController.class, Entity.class )
@ComponentScan("test.firstproject")
@EntityScan(basePackages = "test.firstproject.entities")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@EnableJpaRepositories("test.firstproject.repository")
@EnableAutoConfiguration
public class TestController

private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController).build();

public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

@Autowired
private ObjectMapper objectMapper;


@Test
public void allEntities()
this.objectMapper = new ObjectMapper();
try
ResultActions resultActions = this.mvc
.perform(MockMvcRequestBuilders.get("/welcome").accept(MediaType.APPLICATION_JSON));
this.mvc.perform(get("/welcome")).andExpect(status().isOk());
MvcResult result = resultActions.andReturn();
List<Object> list = objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<Entity>>());
for (Object c : list)
assertTrue(c.getClass().equals(Entity.class));


catch (Exception e)
e.printStackTrace();






First, it threw NullPointerException when calling service.getEntities(). Then I've tried by initializing the service doing = new MyService(), but this time return repository.findAll(); throws the error. What's wrong?



EDIT - Stacktrace



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: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 com.example.demo.TestController.getAllEntities(TestController.java:58)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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.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 com.springmiddleware.controllers.MyController.allEntities(MyController.java:32)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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)
... 40 more









share|improve this question
















I am testing a simple beginner spring boot application, but it keeps throwing NullPointerException for my service class and my repository class.

This is my controller class:



@EnableAutoConfiguration
@RestController
public class MyController

@Autowired
private MyService service;


@GetMapping("/welcome")
public String home throws IOException
return service.getEntities();





This is the Service class:



@EnableAutoConfiguration
@Service
public class MyService{

@Autowired(required=true)
private MyRepository repository;

public MyService()
;

public List<Entity> getEntities() throws IOException
return repository.findAll();



And this is the repository:



@Repository
public interface MyRepository extends JpaRepository<Entity, Long>

List<Entity> findAll();




So, if I run the application everything is ok. The problem is when I run this test:



@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyService.class, MyController.class, Entity.class )
@ComponentScan("test.firstproject")
@EntityScan(basePackages = "test.firstproject.entities")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@EnableJpaRepositories("test.firstproject.repository")
@EnableAutoConfiguration
public class TestController

private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController).build();

public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

@Autowired
private ObjectMapper objectMapper;


@Test
public void allEntities()
this.objectMapper = new ObjectMapper();
try
ResultActions resultActions = this.mvc
.perform(MockMvcRequestBuilders.get("/welcome").accept(MediaType.APPLICATION_JSON));
this.mvc.perform(get("/welcome")).andExpect(status().isOk());
MvcResult result = resultActions.andReturn();
List<Object> list = objectMapper.readValue(result.getResponse().getContentAsString(), new TypeReference<List<Entity>>());
for (Object c : list)
assertTrue(c.getClass().equals(Entity.class));


catch (Exception e)
e.printStackTrace();






First, it threw NullPointerException when calling service.getEntities(). Then I've tried by initializing the service doing = new MyService(), but this time return repository.findAll(); throws the error. What's wrong?



EDIT - Stacktrace



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: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 com.example.demo.TestController.getAllEntities(TestController.java:58)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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.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 com.springmiddleware.controllers.MyController.allEntities(MyController.java:32)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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)
... 40 more






java spring-boot






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 17:01







MoM

















asked Mar 28 at 16:42









MoMMoM

73 bronze badges




73 bronze badges















  • Please can you post the stack trace so we can see where the NPE comes from?

    – Not a JD
    Mar 28 at 16:51











  • @NotaJD added the stacktrace

    – MoM
    Mar 28 at 16:56











  • MockMvcBuilders.standaloneSetup(new MyController) is that valid?

    – Antoniossss
    Mar 28 at 16:57











  • What is "MyController.allEntities"? I see it in the stacktrace but not in the code

    – Not a JD
    Mar 28 at 17:00

















  • Please can you post the stack trace so we can see where the NPE comes from?

    – Not a JD
    Mar 28 at 16:51











  • @NotaJD added the stacktrace

    – MoM
    Mar 28 at 16:56











  • MockMvcBuilders.standaloneSetup(new MyController) is that valid?

    – Antoniossss
    Mar 28 at 16:57











  • What is "MyController.allEntities"? I see it in the stacktrace but not in the code

    – Not a JD
    Mar 28 at 17:00
















Please can you post the stack trace so we can see where the NPE comes from?

– Not a JD
Mar 28 at 16:51





Please can you post the stack trace so we can see where the NPE comes from?

– Not a JD
Mar 28 at 16:51













@NotaJD added the stacktrace

– MoM
Mar 28 at 16:56





@NotaJD added the stacktrace

– MoM
Mar 28 at 16:56













MockMvcBuilders.standaloneSetup(new MyController) is that valid?

– Antoniossss
Mar 28 at 16:57





MockMvcBuilders.standaloneSetup(new MyController) is that valid?

– Antoniossss
Mar 28 at 16:57













What is "MyController.allEntities"? I see it in the stacktrace but not in the code

– Not a JD
Mar 28 at 17:00





What is "MyController.allEntities"? I see it in the stacktrace but not in the code

– Not a JD
Mar 28 at 17:00












1 Answer
1






active

oldest

votes


















0
















You created MyController using new in line:



private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController()).build();


Spring probably not injected Service to it. Try autowire:



@Autowired
private MyController myController;


And move MockMvc instantiation to @Before method:



private MockMvc mvc;

@Before
public void initialize()
mvc = MockMvcBuilders.standaloneSetup(myController).build();






share|improve this answer



























  • It throws nullpointer exception in MockMvc builder

    – MoM
    Mar 28 at 16:58











  • I edited answer, move MockMvc builder in @Before method.

    – Mikhail Efimov
    Mar 28 at 17:01











  • Thanks a lot, that worked!

    – MoM
    Mar 28 at 17:02













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/4.0/"u003ecc by-sa 4.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%2f55402860%2fspring-boot-autowired-service-and-repository-throwing-nullpointerexception%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
















You created MyController using new in line:



private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController()).build();


Spring probably not injected Service to it. Try autowire:



@Autowired
private MyController myController;


And move MockMvc instantiation to @Before method:



private MockMvc mvc;

@Before
public void initialize()
mvc = MockMvcBuilders.standaloneSetup(myController).build();






share|improve this answer



























  • It throws nullpointer exception in MockMvc builder

    – MoM
    Mar 28 at 16:58











  • I edited answer, move MockMvc builder in @Before method.

    – Mikhail Efimov
    Mar 28 at 17:01











  • Thanks a lot, that worked!

    – MoM
    Mar 28 at 17:02















0
















You created MyController using new in line:



private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController()).build();


Spring probably not injected Service to it. Try autowire:



@Autowired
private MyController myController;


And move MockMvc instantiation to @Before method:



private MockMvc mvc;

@Before
public void initialize()
mvc = MockMvcBuilders.standaloneSetup(myController).build();






share|improve this answer



























  • It throws nullpointer exception in MockMvc builder

    – MoM
    Mar 28 at 16:58











  • I edited answer, move MockMvc builder in @Before method.

    – Mikhail Efimov
    Mar 28 at 17:01











  • Thanks a lot, that worked!

    – MoM
    Mar 28 at 17:02













0














0










0









You created MyController using new in line:



private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController()).build();


Spring probably not injected Service to it. Try autowire:



@Autowired
private MyController myController;


And move MockMvc instantiation to @Before method:



private MockMvc mvc;

@Before
public void initialize()
mvc = MockMvcBuilders.standaloneSetup(myController).build();






share|improve this answer















You created MyController using new in line:



private MockMvc mvc = MockMvcBuilders.standaloneSetup(new MyController()).build();


Spring probably not injected Service to it. Try autowire:



@Autowired
private MyController myController;


And move MockMvc instantiation to @Before method:



private MockMvc mvc;

@Before
public void initialize()
mvc = MockMvcBuilders.standaloneSetup(myController).build();







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 28 at 17:00

























answered Mar 28 at 16:56









Mikhail EfimovMikhail Efimov

3437 bronze badges




3437 bronze badges















  • It throws nullpointer exception in MockMvc builder

    – MoM
    Mar 28 at 16:58











  • I edited answer, move MockMvc builder in @Before method.

    – Mikhail Efimov
    Mar 28 at 17:01











  • Thanks a lot, that worked!

    – MoM
    Mar 28 at 17:02

















  • It throws nullpointer exception in MockMvc builder

    – MoM
    Mar 28 at 16:58











  • I edited answer, move MockMvc builder in @Before method.

    – Mikhail Efimov
    Mar 28 at 17:01











  • Thanks a lot, that worked!

    – MoM
    Mar 28 at 17:02
















It throws nullpointer exception in MockMvc builder

– MoM
Mar 28 at 16:58





It throws nullpointer exception in MockMvc builder

– MoM
Mar 28 at 16:58













I edited answer, move MockMvc builder in @Before method.

– Mikhail Efimov
Mar 28 at 17:01





I edited answer, move MockMvc builder in @Before method.

– Mikhail Efimov
Mar 28 at 17:01













Thanks a lot, that worked!

– MoM
Mar 28 at 17:02





Thanks a lot, that worked!

– MoM
Mar 28 at 17:02




















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%2f55402860%2fspring-boot-autowired-service-and-repository-throwing-nullpointerexception%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

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해