13

以下是服务。

@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?

4

2 回答 2

12

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

于 2015-01-05T12:55:45.507 回答
2

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

@RunWith(SpringRunner.class )
@SpringBootTest
public class ProtocolTransactionServiceTest {

    @Autowired
    private ProtocolTransactionService protocolTransactionService;
}

@SpringBootTest加载整个上下文。

于 2020-07-07T12:01:21.217 回答