Spring、Spring Boot和TestNG測試指南 – 共享測試配置

chanjarster發表於2017-09-06

Github地址

使用Spring Boot Testing工具中提到:

在測試程式碼之間儘量做到配置共用。

能夠有效利用Spring TestContext Framework的快取機制,ApplicationContext只會建立一次,後面的測試會直接用已建立的那個,加快測試程式碼執行速度。

本章將列舉幾種共享測試配置的方法

@Configuration

我們可以將測試配置放在一個@Configuration裡,然後在測試@SpringBootTest或ContextConfiguration中引用它。

PlainConfiguration

@SpringBootApplication(scanBasePackages = "me.chanjar.shareconfig")
public class PlainConfiguration {
}

FooRepositoryIT

@SpringBootTest(classes = PlainConfiguration.class)
public class FooRepositoryIT extends ...

@Configuration on interface

也可以把@Configuration放到一個interface上。

PlainConfiguration

@SpringBootApplication(scanBasePackages = "me.chanjar.shareconfig")
public interface InterfaceConfiguration {
}

FooRepositoryIT

@SpringBootTest(classes = InterfaceConfiguration.class)
public class FooRepositoryIT extends ...

Annotation

也可以利用Spring的Meta-annotations自定義機制,提供自己的Annotation用在測試配置上。

PlainConfiguration

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@SpringBootApplication(scanBasePackages = "me.chanjar.shareconfig")
public @interface AnnotationConfiguration {
}

FooRepositoryIT

@SpringBootTest(classes = FooRepositoryIT.class)
@AnnotationConfiguration
public class FooRepositoryIT extends ...

參考文件

相關文章