@Autowired objects are null only when testing

22,863

standaloneSetup is used for unit tests. But it seems like you are doing integrations tests, so the below code should work - I have not tested it.

Replace

@Before
public void setup() throws Exception {
    mockMvc = standaloneSetup(new MetricAPI()).build();
}

with

@Autowired
private WebApplicationContext wac;

@Before
public void setup() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}

and add this to your test class:

@WebAppConfiguration

Bonus

@RunWith(SpringRunner.class) tells JUnit to run using Spring’s testing support. SpringRunner is the new name for SpringJUnit4ClassRunner, it’s just a bit easier on the eye.

Share:
22,863
Doctor Parameter
Author by

Doctor Parameter

I'm a software developer working in the Aerospace industry living in Melbourne, FL. Recent UCF graduate, December 2013 w/ BS in IT.

Updated on March 31, 2020

Comments

  • Doctor Parameter
    Doctor Parameter about 4 years

    My question has to do with the application set-up, not mocking or using autowiring. See the answer for more details.

    I'm trying to set up a Spring Boot application and I'm having issues creating unit tests. My issue is that all objects I have @Autowired are null only during unit testing. When I run the application normally I'm able to use CURL for and it works. However when I test with JUnit I get a null pointer when I try to use the @Autowired objects. I am not using a xml file to configure my beans, maybe that is my problem?

    Application.java

    package com.blakeparmeter.metricsapi;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     *
     * @author Blake
     */
    @SpringBootApplication
    @EnableAutoConfiguration
    public class Application {
    
        public static void main(String[] args){
            SpringApplication.run(Application.class, args);
        }
    }
    

    MetricApi.java

    package com.blakeparmeter.metricsapi.api;
    
    import com.blakeparmeter.metricsapi.beans.Metric;
    import com.blakeparmeter.metricsapi.controllers.MetricController;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * Handles all the REST responses logic of the Metrics services. 
     * Complex logic should be moved outside of this class.
     * @author Blake
     */
    @RestController
    @EnableAutoConfiguration
    public class MetricAPI {
    
        @Autowired 
        private MetricController metricController;
    
        @RequestMapping("/addMetric")
        public ResponseEntity<?> addMetric(@RequestBody Metric record){
            metricController.addMetric(record);
            return ResponseEntity.ok().build();
        }
    }
    

    MetricController.java

    package com.blakeparmeter.metricsapi.controllers;
    
    import com.blakeparmeter.metricsapi.beans.Metric;
    import org.springframework.stereotype.Controller;
    
    /**
     *
     * @author Blake
     */
    @Controller
    public class MetricController {
    
        public Metric addMetric(Metric metric){
            System.out.println("Adding a metric!");
            return metric;
        }
    }
    

    MetricsTest.java

    package metrics;
    
    import com.blakeparmeter.metricsapi.Application;
    import com.blakeparmeter.metricsapi.api.MetricAPI;
    import com.blakeparmeter.metricsapi.beans.Metric;
    import com.fasterxml.jackson.databind.ObjectMapper;
    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.http.MediaType;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.web.servlet.MockMvc;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
    import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
    
    /**
     * @author Blake 
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = Application.class)
    public class MetricsTest {
    
        private MockMvc mockMvc;
    
        @Autowired
        ObjectMapper objectMapper;
    
        @Before
        public void setup() throws Exception {
            mockMvc = standaloneSetup(new MetricAPI()).build();
        }
    
        /**
         * Adds a valid metric
         * @throws Exception 
         */
        @Test
        public void addMetricTest() throws Exception{
            mockMvc.perform(post("/addMetric")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(new Metric())))
                    .andExpect(status().isOk());
        }
    }
    

    pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.blakeparmeter</groupId>
        <artifactId>MetricsAPI</artifactId>
        <version>1.0-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <properties>
            <java.version>1.8</java.version>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>1.7</maven.compiler.source>
            <maven.compiler.target>1.7</maven.compiler.target>
        </properties>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.1.RELEASE</version>
        </parent>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
            </dependency>
            <dependency>
                <groupId>com.h2database</groupId>
                <artifactId>h2</artifactId>
            </dependency>
        </dependencies>
    </project>
    

    Stack trace:

    Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 13.569 sec <<< FAILURE! - in metrics.MetricsTest
    addMetricTest(metrics.MetricsTest)  Time elapsed: 0.174 sec  <<< ERROR!
    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
        at com.blakeparmeter.metricsapi.api.MetricAPI.addMetric(MetricAPI.java:30)
        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:205)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
        at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
        at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
        at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
        at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
        at metrics.MetricsTest.addMetricTest(MetricsTest.java:47)