您的位置:首页 > 编程语言 > Java开发

Spring Boot Unit Test

2017-11-14 12:15 411 查看

Nested Configuration Class

If we just want to test a simple component, we can use @RunWith(SpringRunner.class) along with @TestConfiguration on an inner static class.

@RunWith(SpringRunner.class)
public class SimpleComponentTest {

@TestConfiguration
@ComponentScan(basePackages = {
"com.sap.mcp.collaboration.mapper",
"com.sap.mcp.common.mapper"
})
static class MapperTestContextConfiguration {
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
}
}


The key point in the above code snippet is the @TestConfiguration, quote from spring reference doc:

If you want to customize the primary configuration, you can use a nested @TestConfiguration class. Unlike a nested @Configuration class which would be used instead of a your application’s primary configuration, a nested @TestConfiguration class will be used in addition to your application’s primary configuration.

In other word, if you’re using @Configuration on a nested static class then this nested class is your primary configuration class which doesn’t require an additional @SpringBootConfiguration class. But if you’re using @TestConfiguration on a nested static class then this configuration is just a complement to your primary configuration but with higher priority, and it requires you have a class annotated with @SpringBootConfiguration.

If you’re using any Spring Boot ***Test @interface such @SpringBootTest, @DataJpaTest and so on without nested configuration class, Spring boot will auto search @Configuration class for you.

Remember that even inner @Configuration or @TestConfiguration will be scaned as configuration if they’re included in scan packages. And it’s very likely that test cases’ configuration will affect each other if the test package has the same name as production package.

Test Component

@TestConfiguration and @TestComponent

Test component can be used to define additional beans or

customizations for a test. Unlike regular @Configuration classes the use of

@code @TestConfiguration does not prevent auto-detection of @SpringBootConfiguration

Test component will be excluded during component scan if you are using @SpringBootApplication, because @ComponentScan(excludeFilters = {

@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class) and Spring has provided a default implementation named TestTypeExcludeFilter. So remember to add TypeExcludeFilter if you’re not using @SpringBootApplication

Fine-tunning Test Configuration

Auto-configuration customization

Classpath scanning tunning

Test bootstrap

Detail see https://spring.io/blog/2016/08/30/custom-test-slice-with-spring-boot-1-4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息