I'm receiving a Null Pointer Exception when injecting a @Service into a @SpringBootTest (part of a Spring Boot 2 application).
Here is the skeleton of the Service class:
@Service
public class CustomerService {
    public Customer insertCustomer(Customer customer){
        /* Logic here */ 
        return  customer;
    }
}
And the Test class:
@SpringBootTest
public class CustomerTest {
   @Autowired
   CustomerService service;
   @Test
    public void testDiscount() {
        Customer customer1 = new Customer("ABC"); 
        service.insertCustomer(customer1);   
        assertEquals(5, customer1.getDiscount());
    }
}
Do I miss any other annotation in the test class to make it working? Thanks
You should add @RunWith(SpringRunner.class) at test class level to load all necessary beans. And also make sure your package name to avoid @ComponentScan annotation.
So simply you can do like this:
under src/main/java
package com.customer.service;
@Service
public class CustomerService {
   public Customer insertCustomer(Customer customer) {
        /* Logic here */ 
        return  customer;
   }
}
under src/test/java
package com.customer.service;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerTest {
   @Autowired
   CustomerService service;
   @Test
   public void testDiscount() {
        Customer customer1 = new Customer("ABC"); 
        service.insertCustomer(customer1);   
        assertEquals(5, customer1.getDiscount());
   }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With