在 Spring 引导中排除配置 class 进行集成测试扫描

Excluding config class from being scanned for integration test in Spring Boot

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

我希望这个新的集成测试 class 不命中我的端点测试配置 class 但它目前正在这样做,即使它不是自动连接的并且它导致 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(){


        }
    }

虽然这不起作用,因为我的端点配置 class 不是自动配置。

如何设置它以忽略 class?我可以使用 Maven 插件在 pom.xml 中完成吗?我最终想要它,所以当我 运行 mvn 验证它只是 运行s 集成测试但首先我希望它忽略我的配置 class.

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

@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(){


            }
        }

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

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

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

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