代码之家  ›  专栏  ›  技术社区  ›  Florian

无法在测试中自动关联依赖项

  •  0
  • Florian  · 技术社区  · 7 年前

    我想写一个Spring集成测试来确保 @Autowired

    考试班

    @RunWith(SpringRunner.class)
    @DataJpaTest
    @EntityScan(basePackageClasses = {ClassUnderTest.class, SomRepository.class, SomeEntity.class})
    public class ClassUnderTestIT{
    
        @Autowired private InterfaceUnderTest cut;
    
        @Test public void autowires() {
            assertThat(cut).isNotNull();
        }
    
    }
    

    应该测试一下这个 @Service

    @Service
    @Transactional
    public class ClassUnderTest implements InterfaceUnderTest {
    
        private final SomeRepository repository;
    
        @Autowired
        public DefaultWatchlistDataModifier(SomeRepository repository) {
            this.repository = repository;
        }
    
    }
    

    特别注意有线依赖关系

    @Repository
    @Transactional(readOnly = true)
    @Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
    public interface SomeRepository extends JpaRepository<SomeEntity, String> {
    }
    

    然而,我得到的只是一个例外

    org.springframework.beans.factory.NoSuchBeanDefinitionException:
    No qualifying bean of type 'com.[...].InterfaceUnderTest' available:
    expected at least 1 bean which qualifies as autowire candidate.
    Dependency annotations: 
    {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    

    同时,我还尝试了各种附加注释,例如 @ComponentScan @EnableJpaRepositories ... 无论我能从无数关于这个话题的问题中挖掘出什么,都是徒劳的。

    1 回复  |  直到 7 年前
        1
  •  3
  •   M. Deinum    7 年前

    使用[ @DataJpaTest ]将只引导Spring引导应用程序的JPA部分。由于测试单元不是该子集的一部分,因此它在应用程序上下文中不可用。

    @SpringBootTest

    推荐文章