为什么@TestConfiguration不为我的测试创建bean?

问题描述 投票:0回答:1

我的服务

@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实际上为空。

spring spring-boot junit5 spring-test
1个回答
0
投票

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

我已经更新了您的代码,并且现在可以正常工作(在类路径上为junit 5)。如果dat您正在使用junit 4,则应为@RunWith(SpringRunner.class)而不是@ExtendWith(SpringExtension.class)

@ExtendWith(SpringExtension.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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.