@DataJpaTest needing a class outside the test

前端 未结 1 1937
失恋的感觉
失恋的感觉 2021-02-07 03:13

In a SpringBoot application, I would like to do some test about the repository layer.

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


        
相关标签:
1条回答
  • 2021-02-07 03:40

    The problem is that your @SpringBootApplication has some additional configuration regarding scheduling and by adding that there and not having a custom @SpringBootConfiguration for your test, such scheduling requirement becomes mandatory for everything.

    Let's take a step back. When you add @DataJpaTest, Spring Boot needs to know how to bootstrap your application context. It needs to find your entities and your repositories. Slice tests will recursively search for a @SpringBootConfiguration: first in the package of your actual test, then the parent, then the parent and if it doesn't find one it will throw an exception.

    @SpringBootApplication is a @SpringBootConfiguration so if you don't do anything special, slice tests will use your app as the source for configuration (which is IMO, an excellent default).

    Slice tests do not blindly start you app (otherwise that wouldn't be slicing) so what we do is disable auto-configuration and customize component scan for the task at hand (only scanning entities and repositories and ignoring all the rest when you use @DataJpaTest). That's a problem for you since the application configuration is applied and the scheduling stuff should be available. But dependent beans aren't scanned.

    In your case, if you want to use slicing the scheduling configuration should move to a SchedulingConfiguration or something (it won't be scanned with slicing as explained above). Regardless, I think it's cleaner to separate a SchedulingConfigurer implementation anyway. If you do that, you'll notice the error will go away.

    Let's assume now that you want for that particular test that FooService is also available. Rather than enabling component scan as dimitrisli suggested (that's basically disabling slicing for your configuration), you can just import the missing class

    @RunWith(SpringRunner.class)
    @DataJpaTest
    @Import(FooService.class)
    public class VisitRepositoryTest {
      ...
    }
    
    0 讨论(0)
提交回复
热议问题