@DataJpaTest需要在测试之外的类
在SpringBoot应用程序中,我想对存储库层进行一些测试。
@RunWith(SpringRunner.class) @DataJpaTest public class VisitRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private VisitRepository visitRepository; ... }
当我尝试从VisitRepositoryTest
运行测试时,我收到有关DefaultConfigService
的错误
com.norc.Application中的字段defaultConfigService需要一个无法找到的类型为“com.norc.service.DefaultConfigService”的bean。
那么这需要运行Application
吗?
我试图在VisitRepositoryTest
放置一个DefaultConfigService
bean,但是不允许这样做。
这个类在我的应用程序中使用
@EntityScan(basePackageClasses = {Application.class, Jsr310JpaConverters.class}) @SpringBootApplication @EnableScheduling public class Application implements SchedulingConfigurer { @Autowired private DefaultConfigService defaultConfigService; ... }
如何管理?
编辑
在我的应用程序中,我在cron选项卡中使用此类:
@Service public class DefaultConfigServiceImpl implements DefaultConfigService { private final DefaultConfigRepository defaultConfigRepository; @Autowired public DefaultConfigServiceImpl(final DefaultConfigRepository defaultConfigRepository) { this.defaultConfigRepository = defaultConfigRepository; } }
问题是你的@SpringBootApplication
有一些关于调度的附加配置,并且通过添加它而没有为你的测试定制@SpringBootConfiguration
,这样的调度要求对于一切都是必需的。
我们退一步吧。 添加@DataJpaTest
,Spring Boot需要知道如何引导应用程序上下文。 它需要找到您的实体和您的存储库。 切片测试将以递归方式搜索@SpringBootConfiguration
:首先在实际测试的包中,然后是父级,然后是父级,如果找不到,则会抛出exception。
@SpringBootApplication
是一个@SpringBootConfiguration
所以如果你不做任何特别的事情,切片测试将使用你的app作为配置源(这是IMO,一个很好的默认值)。
切片测试不会盲目地启动你的应用程序(否则不会切片)所以我们所做的是禁用自动配置并为手头的任务定制组件扫描(仅扫描实体和存储库,并在使用@DataJpaTest
时忽略所有其余部分) @DataJpaTest
)。 这是一个问题,因为应用了应用程序配置并且调度内容应该可用。 但是不会扫描依赖的bean。
在您的情况下,如果您想使用切片,则调度配置应移至SchedulingConfiguration
或其他东西(不会像上面所解释的那样使用切片进行扫描)。 无论如何,我认为分离SchedulingConfigurer
实现更加清晰。 如果你这样做,你会发现错误会消失。
现在让我们假设您希望FooService
也可用于该特定测试。 而不是像dimitrisli建议的那样启用组件扫描(这基本上禁用了对您的配置的切片),您可以只导入缺少的类
@RunWith(SpringRunner.class) @DataJpaTest @Import(FooService.class) public class VisitRepositoryTest { ... }