java – 在JUnit测试中自动装配Spring服务

前端之家收集整理的这篇文章主要介绍了java – 在JUnit测试中自动装配Spring服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有以下Spring服务:

@Service
public class MyService  {
   public List

和配置类:

@Configuration
public static class MyApplicationContext {

    @Bean
    public Filter filter(ApplicationContext context) {
        return new Filter();
    }
}

现在,我想创建一个单元测试来检查getIds方法是否返回正确的结果.我创建了以下JUnit测试:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=MyApplicationContext.class,loader=AnnotationConfigContextLoader.class)
public class AppTest
{
    @Autowired
    Filter filter;

    @Autowired
    MyService service;
}

编译器为Filter类找到正确的bean,但是为服务变量抛出“BeanCreationException:Could not autowire field”异常.我尝试将服务类添加到ContextConfiguration.classes,但随后编译器抛出“IllegalStateException:无法加载ApplicationContext”异常.

如何在ContextConfiguration中包含MyService?

@H_404_29@
最佳答案@H_404_29@
将以下注释添加到MyApplicationContext以获取要扫描的服务@ComponentScan(“myservice.package.name”)@H_404_29@ 原文链接:https://www.f2er.com/spring/432697.html

猜你在找的Spring相关文章