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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27779885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:22:54  来源:igfitidea点击:

Autowire a Spring service in JUnit test

javaspringjunitspring-junit

提问by orwe

I have a following Spring service:

我有以下 Spring 服务:

@Service
public class MyService  {
   public List<int> getIds(Filter filter){
      ...
   }
}

and a configuration class:

和一个配置类:

@Configuration
public static class MyApplicationContext {

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

Now, I'd like to create a unit test to check if the getIds method returns correct results. I created a following JUnit test:

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

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

    @Autowired
    MyService service;
}

The compiler finds the correct bean for the Filter class but throws the "BeanCreationException: Could not autowire field" exception for the service variable. I tried to add the service class to the ContextConfiguration.classes but then the compiler thrown "IllegalStateException: Failed to load ApplicationContext" exception.

编译器为 Filter 类找到正确的 bean,但为服务变量抛出“BeanCreationException:无法自动装配字段”异常。我试图将服务类添加到 ContextConfiguration.classes 但随后编译器抛出了“IllegalStateException: Failed to load ApplicationContext”异常。

How to include MyService in the ContextConfiguration?

如何在 ContextConfiguration 中包含 MyService?

回答by bachr

Add the following annotation to MyApplicationContextfor the service to be scanned @ComponentScan("myservice.package.name")

MyApplicationContext为要扫描的服务添加如下注解@ComponentScan("myservice.package.name")