@DataJpaTest 在测试之外需要一个 class

@DataJpaTest needing a class outside the test

在一个SpringBoot应用中,我想对repository层做一些测试。

@RunWith(SpringRunner.class)
@DataJpaTest
public class VisitRepositoryTest {

     @Autowired
     private TestEntityManager entityManager;

     @Autowired
     private VisitRepository visitRepository;

     ...
}

当我尝试从 VisitRepositoryTest 进行 运行 测试时,我收到关于 DefaultConfigService

的错误

Field defaultConfigService in com.norc.Application required a bean of type 'com.norc.service.DefaultConfigService' that could not be found.

所以这需要 运行 Application?

我试过在VisitRepositoryTest中放一个DefaultConfigService的bean,但是不允许

这个class在我的应用程序中使用

@EntityScan(basePackageClasses = {Application.class, Jsr310JpaConverters.class})
@SpringBootApplication
@EnableScheduling
public class Application implements SchedulingConfigurer {

      @Autowired
      private DefaultConfigService defaultConfigService;
      ...
}

如何管理?


编辑

在我的应用程序中,我在 cron 选项卡中使用此 class:

@Service
public class DefaultConfigServiceImpl implements DefaultConfigService {

    private final DefaultConfigRepository defaultConfigRepository;

    @Autowired
    public DefaultConfigServiceImpl(final DefaultConfigRepository defaultConfigRepository) {
         this.defaultConfigRepository = defaultConfigRepository;
    }
}

问题是您的 @SpringBootApplication 有一些关于计划的额外配置,并且通过在那里添加并且没有自定义 @SpringBootConfiguration 用于您的测试,这样的计划要求对所有事情都是强制性的。

让我们退一步。当您添加 @DataJpaTest 时,Spring Boot 需要知道如何 bootstrap 您的应用程序上下文。它需要找到您的实体和存储库。切片测试将递归搜索 @SpringBootConfiguration:首先在您的实际测试包中,然后是父级,然后是父级,如果找不到,它将抛出异常。

@SpringBootApplication 是一个 @SpringBootConfiguration 所以如果你不做任何特别的事情,切片测试将使用你的应用程序作为配置源(这是 IMO,一个很好的默认值)。

切片测试不会盲目地启动你的应用程序(否则不会切片)所以我们所做的是禁用自动配置并为手头的任务自定义组件扫描(只扫描实体和存储库并忽略所有使用 @DataJpaTest 时休息)。这对您来说是个问题,因为应用程序配置已应用并且调度内容应该可用。但是不扫描依赖 bean。

在你的情况下,如果你想使用切片,调度配置应该移动到 SchedulingConfiguration 或其他东西(它不会像上面解释的那样用切片扫描)。无论如何,我认为无论如何分离 SchedulingConfigurer 实现更清晰。如果这样做,您会发现错误会消失。

现在假设您希望针对该特定测试 FooService 也可用。而不是像 dimitrisli 建议的那样启用组件扫描(这基本上是为您的配置禁用切片),您可以只导入丢失的 class

@RunWith(SpringRunner.class)
@DataJpaTest
@Import(FooService.class)
public class VisitRepositoryTest {
  ...
}