BustedSanta
BustedSanta

Reputation: 1388

Spring RESTful (Gradle) : @Autowired results in NullPointerException

Please know that I have researched this issue extensively both on this website and elsewhere but the suggested solutions didn't work for me.

I can run the Spring application itself without issues (bootRun) therefore I assume this is only jUnit related issue. When I try to run either Gradle test or JUnit test on the SearchControllerUnitTest class, I end up with NullPointerException.

Can anyone please point out where my configuration is incorrect?

Thank you!

SearchControllerUnitTest.java

    @Category(UnitTest.class)
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = AppConfig.class)
    public class SearchControllerUnitTest extends UnitTest {

        private MockMvc mockMvc;

        @Override
        @Before
        public void setUp() {
            super.setUp();
            mockMvc = MockMvcBuilders.standaloneSetup(new SearchController()).build();
        }

    @Test
    public void getProductTest() throws Exception {
        . . . 
    }

SearchController.java

    @RestController
    public class SearchController {

        public static final Logger log = LoggerFactory.getLogger(SearchController.class);

        @Autowired
        Product product; // <<< autowiring not working in jUnit only

        @Autowired
        ProductService productService; // <<< autowiring not working in jUnit only

        @RequestMapping(value = "/search", method = RequestMethod.GET, produces = "application/json")
        public ResponseEntity<Product> getProduct(@RequestParam(value = "name", required = true) String name) {

            if (productService == null) {
                log.info("productService is null!!");
            }
            . . .

            product = productService.getProduct(name);  // <<<< NPE here
        }

ProductService.java

    public interface ProductService {
        . . .
        public Product getProduct(String productName);
        . . .
    }

ProductServiceImpl.java

    @Service
    public class ProductServiceImpl implements ProductService {

        public Product getProduct(String productName){
            . . .   
        }

    }

Exception:

Caused by: java.lang.NullPointerException
    at com.somepckagename.controller.SearchController.getProduct(SearchController.java:36)

Upvotes: 0

Views: 309

Answers (1)

dunni
dunni

Reputation: 44545

You are creating the instance of the SearchController yourself in the line mockMvc = MockMvcBuilders.standaloneSetup(new SearchController()).build();. If you do that, autowiring will of course not work because Spring doesn't know it's a bean.

Instead create a field in your test to inject the controller:

@Autowired
private SearchController controller;

and use that instance. Also that's the perfect reason to use constructor injection instead of field injection.

Upvotes: 1

Related Questions