spring单元测试中的模拟bean未连接到自动连接依赖项
我试图为一个具有自动连接依赖项的类编写单元测试spring单元测试中的模拟bean未连接到自动连接依赖项,spring,spring-boot,mockito,spring-boot-test,springmockito,Spring,Spring Boot,Mockito,Spring Boot Test,Springmockito,我试图为一个具有自动连接依赖项的类编写单元测试 public class User { @Autowired private ServiceContext serviceContext; User() {} public String getToken() { return serviceContext.getToken(); } 我的单元测试类用于测试getToken()方法 当我运行这个测试时,在User的getToken()中有一个NullPointerException。
public class User {
@Autowired
private ServiceContext serviceContext;
User() {}
public String getToken() {
return serviceContext.getToken();
}
我的单元测试类用于测试getToken()方法
当我运行这个测试时,在User
的getToken()
中有一个NullPointerException。它表示serviceContext
变量为空
为什么我在测试中创建的模拟bean不能自动连接到用户类中的依赖项
我也试过这个测试代码-
@RunWith(SpringJUnit4ClassRunner.class)
public class UserTest() {
@MockBean
private ServiceContext serviceContext;
@InjectMocks
User useer = new User();
@BeforeTest
private void setup() {
when(serviceContext.getToken()).thenReturn("Token");
}
@Test
public void test() {
assertEquals(user.getToken(), "Token");
}
}
这也给出了一个NullPointerException,表示User
类中的serviceContext
依赖项为null
如何使用模拟ServiceContext
bean对我的用户类方法进行单元测试,并将其连接到用户
对象
我正在使用基于注释的spring配置,不想启动spring容器来测试这一点
为了运行我的应用程序,我使用以下命令-
@Configuration
@EnableConfigurationProperties(ApiProperties.class)
public class ServiceConfiguration {
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON, proxyMode = ScopedProxyMode.TARGET_CLASS)
ServiceContext serviceContext(ApiProperties properties, Parameter param) {
final ServiceContext serviceContext = new ServiceContext(properties, param);
return serviceContext;
}
我需要在我的
@SpringBootTest
中添加这个类吗?spring如何知道应该创建哪个上下文
您只定义了测试应该使用spring运行,但是spring不知道从哪里加载配置
如果您想依赖spring引导配置解析规则,或者在某些
@ContextConfiguration
中手动指定要加载的配置,则应使用@springbootest
注释。我是spring的新手。你能分享一些关于我应该在@springbootest
或@ContextConfiguration
中使用什么作为类的建议吗?你应该真正了解这一点,这是一个广泛的主题,远远超出了SO格式。换句话说,这就是指定应该加载什么的方法(spring必须以某种方式解析bean)。首先,尝试不带参数的@SpringBootTest.All-in-All,您可以从这里开始阅读:因此我有一个配置注释类,它声明了ServiceContext
bean。用这部分代码编辑了我的问题。简单地说,类UserTest不是有效的spring启动测试,因为它缺少我在回答中提到的注释之一。应用程序上下文启动时根本没有bean(它们是从未指定的配置加载的),因此它没有任何东西可以自动连接
@Configuration
@EnableConfigurationProperties(ApiProperties.class)
public class ServiceConfiguration {
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON, proxyMode = ScopedProxyMode.TARGET_CLASS)
ServiceContext serviceContext(ApiProperties properties, Parameter param) {
final ServiceContext serviceContext = new ServiceContext(properties, param);
return serviceContext;
}