Carla
Carla

Reputation: 3380

Unable to inject a @Service in a Spring Boot Test


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

Upvotes: 4

Views: 1066

Answers (1)

Satz
Satz

Reputation: 319

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());
   }
}

Upvotes: 3

Related Questions