在Spring Boot测试中无法注入@Service

时间:2019-01-07 09:35:58

标签: spring-boot


将@Service注入@SpringBootTest(Spring Boot 2应用程序的一部分)时,我收到Null指针异常。 这是Service类的骨架:

@Service
public class CustomerService {

    public Customer insertCustomer(Customer customer){
        /* Logic here */ 
        return  customer;

    }

}

和Test类:

@SpringBootTest
public class CustomerTest {


   @Autowired
   CustomerService service;

   @Test
    public void testDiscount() {
        Customer customer1 = new Customer("ABC"); 
        service.insertCustomer(customer1);   
        assertEquals(5, customer1.getDiscount());
    }

}

我是否会错过测试类中的任何其他注释才能使其正常工作? 谢谢

1 个答案:

答案 0 :(得分:2)

您应该在测试类级别添加@RunWith(SpringRunner.class)来加载所有必需的bean。还要确保您的软件包名称避免使用@ComponentScan注释。

因此,您可以简单地这样做:

在src / main / java下

package com.customer.service;

@Service
public class CustomerService {

   public Customer insertCustomer(Customer customer) {
        /* Logic here */ 
        return  customer;
   }
}

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