Spring Boot Unit Test

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值