Spring boot 如何在测试期间覆盖Spring Boot autowired组件

Spring boot 如何在测试期间覆盖Spring Boot autowired组件,spring-boot,spring-batch,Spring Boot,Spring Batch,我正在尝试为Spring Boot批处理应用程序编写测试 我有一个接口“WsaaClient”和两个实现,我需要将其中一个用于正常执行,另一个用于测试 在这个项目中,我有一个FCEClient类,它有一个自动连接字段“LoginManager”,它有一个自动连接字段“WsaaClient” @组件 @配置文件(“!dev”) 公共类FCEClient实现IFCEClient{ @自动连线 LoginManager LoginManager; @组成部分 公共类登录管理器{ @自动连线 WSA

我正在尝试为Spring Boot批处理应用程序编写测试

我有一个接口“WsaaClient”和两个实现,我需要将其中一个用于正常执行,另一个用于测试

在这个项目中,我有一个FCEClient类,它有一个自动连接字段“LoginManager”,它有一个自动连接字段“WsaaClient”

@组件
@配置文件(“!dev”)
公共类FCEClient实现IFCEClient{
@自动连线
LoginManager LoginManager;

@组成部分
公共类登录管理器{
@自动连线
WSAA客户端;
@组件
公共类AfipWsaaClientSpring扩展了AfipWsaaClient{
AfipWsaaClient位于非spring maven依赖项中。它实现WsaaClient

运行Spring批处理应用程序运行良好,并选择了AfipWsaaClientSpring

现在我想编写一个测试,需要为WsaaClient使用一个虚拟实现

所以我把这个类放在src/test/java下面:

@组件
公共类TestWsaaClientSpring实现WsaaClient{
这个测试:

@RunWith(SpringRunner.class)
@春靴测试
@上下文配置
公共类FceBatchApplicationTests{
私有JobLauncherTestUtils JobLauncherTestUtils;
@试验
public void testJob()引发异常{
JobExecution JobExecution=JobLaunchTestUtils.launchJob();
Assert.assertEquals(“已完成”,jobExecution.getExitStatus().getExitCode());
}
}
在Eclipse上从JUnit启动器运行它会引发:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'afipWsaaClientSpring' defined in file [/home/guish/vmshare/eclipsews/ec/ec-batch/target/classes/com/mycompany/AfipWsaaClientSpring.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.mycompany.AfipWsaaClientSpring]: Constructor threw exception; nested exception is java.io.FileNotFoundException: ./wsaa_client.properties (No such file or directory)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1303) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1197) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.8.RELEASE.jar:5.1.8.RELEASE]
FileNotFoundException不相关,该文件不存在,因为它作为测试运行,Spring引导不应选择AfipWsaaClientSpring实现

如何在测试代码中覆盖Autowired选项并选择TestWsaaClientSpring


以防万一,在作为测试运行时,如何防止Spring Boot实例化AfipWsaaClientSpring?

注解@SpringBootTest具有“属性”属性()。 因此,您可以像这样指定弹簧轮廓

@SpringBootTest(properties = {"spring.profiles.active=test"}, classes=MyConfiguration.class)
如前所述,您可以为SpringBootTest提供活动配置文件。您也可以通过FceBatchApplicationTests类上的注释@ActiveProfile(“theprofile”)来实现这一点