【问题标题】:Why did @TestConfiguration not create a bean for my test?为什么@TestConfiguration 没有为我的测试创建一个bean?
【发布时间】:2020-05-28 09:46:32
【问题描述】:

我的服务

@Service
public class StripeServiceImpl implements StripeService {
    @Override
    public int getCustomerId() {
        return 2;
    }
}

我的测试

public class StripeServiceTests {
    @Autowired
    StripeService stripeService;

    @TestConfiguration
    static class TestConfig {

        @Bean
        public StripeService employeeService() {
            return new StripeServiceImpl();
        }
    }

    @Test
    public void findCustomerByEmail_customerExists_returnCustomer() {
        assertThat(stripeService.getCustomerId()).isEqualTo(2);
    }   

}

错误:java.lang.NullPointerException。我查过了,stripeService 实际上是空的。

【问题讨论】:

  • 检查StripeServiceImpl类中是否有@Service注解
  • 是的,当然。我的应用程序仍然可以正常运行。我已经编辑了我的问题。
  • 尝试删除 TestConfig 类并检查。如果您已经自动装配,则无需再次定义 bean。
  • 可能在测试类中缺少@RunWith(SpringRunner.class)(JUnit 4)或@ExtendWith(SpringExtension.class)(JUnit 5)。

标签: spring spring-boot junit5 spring-test


【解决方案1】:

由于您正在自动装配,因此您需要一个 applicationcontext 以便 Spring 可以管理 bean,然后可以将其注入您的类中。因此,您缺少一个注释来为您的测试类创建应用程序上下文。

我已经更新了你的代码,它现在可以工作了(你的类路径上有 junit 5)。如果您使用的是 junit 4,它应该是 @RunWith(SpringRunner.class) 而不是 @ExtendWith(SpringExtension.class)

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = TestConfiguration.class)
public class StripeServiceTests {
    @Autowired
    StripeService stripeService;

    @TestConfiguration
    static class TestConfig {

        @Bean
        public StripeService employeeService() {
            return new StripeServiceImpl();
        }
    }

    @Test
    public void findCustomerByEmail_customerExists_returnCustomer() {
        assertThat(stripeService.getCustomerId()).isEqualTo(2);
    }
}

【讨论】:

  • 您好 Daniel,您的解决方案有效,但我希望使用 @TestConfiguration 仅实例化一个 bean 而不是调出整个应用程序上下文。我会投票而不是标记答案,谢谢。
  • 我已经用一个额外的注释更新了答案。您可以使用 @ContextConfiguration 注释您的类并传递 classes 属性。
猜你喜欢
  • 2019-04-28
  • 2018-05-09
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
相关资源
最近更新 更多