spring - Spring单元测试中的模拟bean未连接到AutoWired依赖项
问题描述
我正在尝试为具有 Autowired 依赖项的类编写单元测试。
public class User {
@Autowired
private ServiceContext serviceContext;
User() {}
public String getToken() {
return serviceContext.getToken();
}
我的单元测试类来测试 getToken() 方法
@RunWith(SpringJUnit4ClassRunner.class)
public class UserTest() {
@MockBean
private ServiceContext serviceContext;
@BeforeTest
private void setup() {
when(serviceContext.getToken()).thenReturn("Token");
}
@Test
public void test() {
User user = new User();
assertEquals(user.getToken(), "Token");
}
}
当我运行这个测试时,有一个 NullPointerException getToken()
。User
它说serviceContext
变量为空。
为什么我在测试中创建的模拟 bean 不能自动连接到 User 类中的依赖项?
我也试过这个测试代码 -
@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 表示类中的serviceContext
依赖User
项为空。
如何使用 bean 对我的 User 类方法进行单元测试mocked ServiceContext
并将其连接到User
对象?
我正在使用基于注释的弹簧配置,并且不想启动弹簧容器来测试它。
为了运行我的应用程序,我正在使用这个 -
@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 不知道从哪里加载配置。
@SpringBootTest
如果您想依赖 Spring Boot 配置解析规则或在某些@ContextConfiguration
情况下手动指定要加载的配置,则应该使用注解。
推荐阅读
- wso2is - WSO2 - IS - 将用户从 WSO2 同步到服务提供商
- javascript - 带有最新制表符的选择编辑器中的问题
- javascript - require.js:如何调试脚本错误?
- javascript - 如何在网站上实现持久的全局导航栏或菜单栏
- python - 在 Flask 中处理 Pandas Dataframe 的最佳方法
- sql-server - 无法从 SQL Server 连接到 Azure Server
- git - 为什么VSCode在gitt diff中插入用^M标记的回车?
- r - 在 face_wrap() ggplot2 中更改构面标签
- go - 带有 http.Get 和 http.ServeFile 的 Golang 意外 EOF
- lisp - LISP - 编写函数 (REMOVE EL),从列表所有级别的另一个列表中删除给定的原子或列表