Spring配置调用两次,所以使用Groovy Spock的Bean

时间:2017-11-02 23:27:22

标签: spring spring-boot groovy spock

我处于奇怪的情况,我们在java和groovy中都有测试用例,但最终会转向groovy。

我有两个抽象类,一个用于java,一个用于spock,如下所示。

@ActiveProfiles(resolver = TestProfileResolver.class)
@IntegrationTest
@IntegrationTestConfiguration(
        applicationStartUpClass = Application.class,
        additionalLocalConfigurationClasses = [LocalIntegrationTestConfiguration.class])
@SpringApplicationConfiguration(classes = [
    LocalIntegrationTestConfiguration.class,
    NonLocalIntegrationTestConfiguration.class,
])
abstract class TestSpec extends Specification {
}

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles(resolver = TestProfileResolver.class)
@IntegrationTest
@IntegrationTestConfiguration(
    applicationStartUpClass = Application.class,
    additionalLocalConfigurationClasses = { LocalIntegrationTestConfiguration.class, Resources.class})
@SpringApplicationConfiguration(classes = {
    LocalIntegrationTestConfiguration.class,
    NonLocalIntegrationTestConfiguration.class,
})
@Component
abstract public class Test {
}

@WebAppConfiguration
@EnableConfigurationProperties({TestProperties.class})
@Import({
    Resources.class,
})
@Profile({"local"})
public class LocalIntegrationTestConfiguration {
    public LocalIntegrationTestConfiguration() {
        System.out.println(" $$$$$ LocalIntegrationTestConfiguration $$$$");
    }
}

问题是LocalIntegrationTestConfiguration被常规spring框架调用两次,然后是spock框架。我希望它只被调用一次。

我想在TESTSPEC中重用TEST上的配置,但不知道如何。任何时髦的专家?

1 个答案:

答案 0 :(得分:1)

这是由弹簧引起的,并且如果你也以这种方式配置两个junit测试也会发生。问题是你正在使用

创建不同的上下文

@IntegrationTestConfiguration( applicationStartUpClass = Application.class, additionalLocalConfigurationClasses = [LocalIntegrationTestConfiguration.class])

和另一个

@IntegrationTestConfiguration( applicationStartUpClass = Application.class, additionalLocalConfigurationClasses = { LocalIntegrationTestConfiguration.class, Resources.class})

请注意额外的Resource.class

如果您希望spring重用上下文,则必须配置相同。有关详细信息,请阅读有关context caching的春季文档。

为什么要使用@Component注释您的测试?