简体   繁体   English

如何先创建一些测试弹簧豆

[英]How to create some test spring beans before others

I have production bean A and in @TestConfiguration bean B. Non of those beans depends on each other. 我有生产bean A,在@TestConfiguration bean B中。这些bean @TestConfiguration But in tests I want bean B to be instantiated before bean A. that's because B prepares local testing environment for A. How can i achieve it? 但是在测试中,我希望在bean A之前实例化beanB。这是因为B为A准备了本地测试环境。我如何实现它?

i can't just annotate A with @DependsOn because B is available only in some tests and i don't want to bind production code with tests. 我不能只用@DependsOn注释A,因为B仅在某些测试中可用,而且我不想将生产代码与测试绑定。

But in tests I want bean B to be instantiated before bean A 但是在测试中,我希望在bean A之前实例化bean B

... ...

and i don't want to bind production code with tests. 而且我不想将生产代码与测试绑定在一起。

Something like this? 像这样吗

@Profile("test")
@Bean
public BeanB beanB() {
    return new BeanB();
}

@Profile("test")
@Bean
public BeanA beanA(BeanB beanB) {
    return new BeanA();
}

@Profile("!test")
@Bean
public BeanA beanA() {
    return new BeanA();
}

There's no easy way to do what you're asking. 没有简单的方法可以完成您要问的事情。 Your best bet is to have an optional dependency in A. In production, the dependency will be missing and so will be ignored. 最好的选择是在A中具有可选的依赖项。在生产中,该依赖项将丢失,因此将被忽略。 In the tests, you will provide a bean which contains your test preparation implementation. 在测试中,您将提供一个包含测试准备实现的bean。

Yes, you are adding a little bit of additional complexity for the sake of tests which is not ideal but it's very limited. 是的,为了测试,您添加了一些额外的复杂性,这虽然不理想,但是非常有限。

Forgive the terrible names: 原谅可怕的名字:

interface APreparer {
    void prepareA();
}

@Component
public class A {
     public A(final Optional<APreparer> preparer) {
          preparer.ifPresent(APreparer::prepareA);
     }
}

You can create a TestApplication (in src/test/java ) that trivially extends your actual Spring Boot application class and have that depend on your test bean. 您可以创建一个TestApplication(在src/test/java ),以简单地扩展实际的Spring Boot应用程序类,并使该类依赖于您的测试bean。 Then tell SpringBootTest to load your TestApplication instead of the production application. 然后告诉SpringBootTest加载您的TestApplication而不是生产应用程序。

Example TestApplication: 示例TestApplication:

@DependsOn("beanB")
@Configuration
@Import(YourApplication.class)
public class TestApplication {}

Example test class: 示例测试类:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class)
public class YourApplicationTests {
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM