【问题标题】:Exclude certain beans when running a junit test运行 junit 测试时排除某些 bean
【发布时间】:2018-10-15 13:11:01
【问题描述】:

所以,我有以下两个 java 测试类:

package com.company.alfresco;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = BuildFileTreeApplication.class)
@Slf4j
public class BuildFileTreeTest {

    @Autowired
    private CmisDao cmisDao;

    @Autowired
    private AlfrescoFileTreeAPI alfrescoFileTreeAPI;

    ...
}

和

package com.company.facade;

@SpringBootTest
@Slf4j
public class EntryPointTest extends AbstractTestNGSpringContextTests{
    private Map<String, String> documentMetadata;

    @Autowired
    private FacadeInitializer facadeInitializer;

    ...
}

我还有两个独立的主方法类,每个测试类使用一个:

package com.company;

@SpringBootApplication
@ComponentScan(basePackages = {"com.company", "com.company.ssh", "com.company.camel",
"com.company.cmis.services", "com.company.facade"})
public class AlfrescoApiApplication {
    public static void main(String[] args){
        SpringApplication.run(AlfrescoApiApplication.class, args);
    }
}

和

package com.company;

@SpringBootApplication
@ComponentScan(basePackages = {"com.company.alfresco", "com.company.models",
    "com.company.config"})
public class BuildFileTreeApplication {
    public static void main(String[] args){
        SpringApplication.run(BuildFileTreeApplication.class, args);
    }
}

我想运行第一个测试(BuildFileTreeTest),而不使用另一个测试正在使用的 bean(FacadeInitializer)。

由于某种原因,使用此包设置,当我运行 BuildFileTreeTest 测试类时,FacadeInitializer bean 仍然在应用程序上下文中使用,尽管它存在于“外观”包中,但我没有这样做'不包括在@ComponentScan 注释中,在BuildFileTreeApplication spring main 方法类中。有什么想法吗?

【问题讨论】:

    标签: java spring junit


    【解决方案1】:

    您可以排除带有类型、注释等的 bean。

    @SpringBootApplication
    @ComponentScan(basePackages = {"com.company.alfresco", "com.company.models", "com.company.config"},
            excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {FacadeInitializer.class})})
    public class BuildFileTreeApplication {
        public static void main(String[] args) {
            SpringApplication.run(BuildFileTreeApplication.class, args);
        }
    }
    

    【讨论】:

    • 我使用了@ComponentScan(basePackages = {"com.company.alfresco", "com.company.models", "com.company.config"}, excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {FacadeInitializer.class})),但该 bean 仍在应用程序上下文中使用。
    • @NarcisNeacsu 你能否给我更多关于“那个豆子仍在使用”的细节。我已经测试了解决方案,根本不会扫描 bean。
    • 基本上我是说正在创建FacadeInitializer 的一个实例,并且它可以用于注入。它没有被忽视。我需要忽略这个bean,因为它依赖于一些目前不可用的外部资源,即使只执行构造函数,我也会得到一个异常。也许我遗漏了一些我忘记包含在问题描述中的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 2016-11-29
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    相关资源
    最近更新 更多