无法在测试中自动装配依赖项

Fail to autowire dependency in test

我想编写一个 Spring 集成测试以确保 @Autowired 正确地组合我的 classes,但是失败了。

测试class

@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 ......无论我在无数关于该主题的 Whosebug 问题中能挖掘到什么 - 所有徒劳无功。

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

要么自己构建并注入依赖项,要么改用完整的 @SpringBootTest