【问题标题】:Autowiring Spring services into JUnit tests将 Spring 服务自动装配到 JUnit 测试中
【发布时间】:2015-03-03 00:17:01
【问题描述】:

以下是服务。

@Service
public class MyService  {
   public List<Integer> getIds(Filter filter){
      // Method body
   }
}

还有一个配置类。

@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 类属性,但这会导致 IllegalStateException: Failed to load ApplicationContext 异常。

如何将 MyService 添加到 ContextConfiguration?

【问题讨论】:

  • 请粘贴完整的堆栈跟踪?你是否也在 xml 中定义了任何 bean 会有所帮助(如果有的话)
  • 您必须tell spring 才能扫描@Service 注释

标签: java spring junit junit4 spring-junit


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    将这两个注解添加到测试类 AppTest 中,如下例所示:

    @RunWith(SpringRunner.class )
    @SpringBootTest
    public class ProtocolTransactionServiceTest {
    
        @Autowired
        private ProtocolTransactionService protocolTransactionService;
    }
    

    @SpringBootTest 加载整个上下文。

    【讨论】:

      猜你喜欢
      • 2015-02-19
      • 2011-06-10
      • 2011-04-09
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 2018-12-01
      • 2020-02-09
      • 1970-01-01
      相关资源
      最近更新 更多