使用@SpringBootTest时如何在测试class中自动装配bean

How to autowire beans in test class when using @SpringBootTest

我有一个集成测试 class 用 @SpringBootTest 注释,它启动了完整的应用程序上下文并让我执行我的测试。但是我无法将 @Autowired beans 放入测试 class 本身。相反,我得到一个错误:

No qualifying bean of type 'my.package.MyHelper' available".

如果我不 @Autowire 我的助手 class,而是将代码直接保留在 setUp 函数中,测试将按预期工作。

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
public class CacheControlTest {

    @Autowired
    private MyHelper myHelper;

    @Before
    public void setUp() {
        myHelper.doSomeStuff();
    }

    @Test
    public void test1() {
        // My test
    }
}

如何在测试 class 中使用 Spring 自动装配,同时还使用 @SpringBootTest

按照@user7294900 下面的建议,创建一个单独的 @Configuration 文件并将其添加到 CacheControlTest 的顶部:

@ContextConfiguration(classes = { CacheControlTestConfiguration.class })

但是,有什么方法可以将配置保留在 CacheControlTest class 本身中吗?我尝试在我的测试中添加 class:

public class CacheControlTest {

    @TestConfiguration
    static class CacheControlTestConfiguration {
        @Bean
        public MyHelper myHelper() {
            return new MyHelper();
        }
    }

}

public class CacheControlTest {

    @Configuration
    static class CacheControlTestConfiguration {
        @Bean
        public MyHelper myHelper() {
            return new MyHelper();
        }
    }
}

但是他们似乎没有任何作用。我仍然遇到同样的错误。如上所述,将相同的配置块放在单独的文件中时仍然有效。

为您的测试添加 ContextConfiguration Class:

@ContextConfiguration(classes = { CacheControlTestConfiguration.class })