Why component scanning does not work for Spring Boot unit tests?

后端 未结 3 859
借酒劲吻你
借酒劲吻你 2021-01-13 19:20

The service class FooServiceImpl is annotated with @Service aka @Component which makes it eligible for autowiring. Why this class is not being pick

3条回答
  •  无人及你
    2021-01-13 19:55

    A unit test should test a component in isolation. You don`t even need to use the Spring Test context framework for a unit test. You can using mocking frameworks such as Mockito, JMock or EasyMock to isolate the dependencies in your component and verify the expectations.

    If you want a true integration test then you need to use the @SpringBootTest annotation on your test class. If you dont specify the classes attribute it loads the @SpringBootApplication annotated class. This results in production components like db connections being loaded.

    To eliminate these define a separate test configuration class which for example defines an embedded database instead of the production one

    @SpringBootTest(classes = TestConfiguration.class)
    public class ServiceFooTest{
    }
    
    @Configuration
    @Import(SomeProductionConfiguration.class)
    public class TestConfiguration{
       //test specific components
    }
    

提交回复
热议问题