首页 > 解决方案 > 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吗?

标签: springspring-bootmockitospring-boot-testspringmockito

解决方案


spring 如何知道应该创建哪个上下文?

您只定义了测试应该使用 spring 运行,但是 spring 不知道从哪里加载配置。

@SpringBootTest如果您想依赖 Spring Boot 配置解析规则或在某些@ContextConfiguration情况下手动指定要加载的配置,则应该使用注解。


推荐阅读