【问题标题】:Excluding config class from being scanned for integration test in Spring Boot在 Spring Boot 中排除配置类以进行集成测试
【发布时间】:2019-12-23 00:14:49
【问题描述】:

我在 Spring Boot 中有多个测试类。我想在我的测试文件夹中创建一个集成测试,其中还包含 4 个单元测试。这 4 个单元测试连接到一个端点测试配置类,该类具有单元测试使用的 bean。

我希望这个新的集成测试类不会命中我的端点测试配置类,但它目前正在这样做,即使它不是自动连接的并且它会导致 bean 实例化错误。

Description:

The bean 'getVersionEndPoint', defined in class path resource [com/nulogix/billing/configuration/EndPointTestConfiguration.class], could not be registered. A bean with that name has already been defined in file [/Users/asluborski/Documents/billing/billing_mediator/target/classes/com/nulogix/billing/ws/endpoint/GetVersionEndPoint.class] and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

我正在考虑找到一种方法让 SpringBootTest 忽略它。我试过这样做:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;

import com.nulogix.billing.App;
import com.nulogix.billing.mockserver.MockServerApp;

@RunWith(SpringRunner.class)
@TestPropertySource(properties=
{"spring.autoconfigure.exclude=comma.seperated.ClassNames,com.nulogix.billing.configuration.EndPointTestConfiguration"})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,classes = {App.class,MockServerApp.class
})
public class BillingMediatorIntegrationTest {

    @Test
    public void testOne(){


        }
    }

这不起作用,因为我的 endpointconfig 类不是 AutoConfig。

如何设置它以忽略课程?我可以使用 Maven 插件在 pom.xml 中执行此操作吗?我最终想要它,所以当我运行 mvn verify 它只运行集成测试但首先我希望它忽略我的配置类。

我尝试过创建一个过滤器,但它似乎也不起作用

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,classes = {MockServerApp.class,App.class
})
@ComponentScan(basePackages = "com.nulogix.billing",
                excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = EndPointTestConfiguration.class))
public class BillingMediatorIT {


        @Test
        public void testOne(){


            }
        }

【问题讨论】:

    标签: maven spring-boot junit configuration integration-testing


    【解决方案1】:

    您可以使用配置文件,它提供了一种从 Spring 上下文中排除类的灵活方法。

    使用 @Profile("test") 注释您的测试配置类 (EndPointTestConfiguration)。除非您激活“测试”配置文件,否则它不会被 Spring 实例化。

    您可以使用@ActiveProfiles 注释在测试中激活配置文件。

    您可以在这里阅读更多内容:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html

    【讨论】:

    • 这行得通。允许将 bean 定义覆盖设置为 true 也可以,但我觉得不推荐这样做,并且可能会导致问题。
    猜你喜欢
    • 2020-05-14
    • 2018-11-02
    • 2021-10-30
    • 1970-01-01
    • 2018-03-21
    • 2015-10-12
    • 2018-02-01
    • 2021-01-24
    • 2020-07-24
    相关资源
    最近更新 更多