本文介绍了无法在 Spring Boot 测试中注入 @Service的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将@Service 注入@SpringBootTest(Spring Boot 2 应用程序的一部分)时,我收到空指针异常.这是 Service 类的骨架:
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;
}
}
和测试类:
@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
推荐答案
您应该在测试类级别添加 @RunWith(SpringRunner.class)
以加载所有必需的 bean.还要确保你的包名避免 @ComponentScan
注释.
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.
所以你可以这样做:
在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());
}
}
这篇关于无法在 Spring Boot 测试中注入 @Service的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!