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

Tar*_*rmo 7 java junit spring spring-test spring-boot

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

没有“my.package.MyHelper”类型的合格 bean 可用”。

如果我没有 @Autowire 我的帮助程序类,而是将代码直接保留在 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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

遵循下面的 @user7294900 建议,创建一个单独的@Configuration文件并将其添加到 CacheControlTest 的顶部是可行的:

@ContextConfiguration(classes = { CacheControlTestConfiguration.class })
Run Code Online (Sandbox Code Playgroud)

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

public class CacheControlTest {

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

}
Run Code Online (Sandbox Code Playgroud)

public class CacheControlTest {

    @Configuration
    static class CacheControlTestConfiguration {
        @Bean
        public MyHelper myHelper() {
            return new MyHelper();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但它们似乎没有任何效果。我仍然遇到同样的错误。不过,如上所述,当放置在单独的文件中时,相同的配置块会起作用。

use*_*900 7

为您的测试类添加 ContextConfiguration:

@ContextConfiguration(classes = { CacheControlTestConfiguration.class })
Run Code Online (Sandbox Code Playgroud)