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

后端 未结 3 852
借酒劲吻你
借酒劲吻你 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:58

    You should use @SpringBootTest(classes=FooServiceImpl.class).

    As it mentioned on Annotation Type SpringBootTest:

    public abstract Class[] classes

    The annotated classes to use for loading an ApplicationContext. Can also be specified using @ContextConfiguration(classes=...). If no explicit classes are defined the test will look for nested @Configuration classes, before falling back to a SpringBootConfiguration search.

    Returns: the annotated classes used to load the application context See Also: ContextConfiguration.classes()

    Default: {}

    This would load only necessary class. If don't specify, it may load a database configuration and other stuff which would make your test slower.

    On the other hand, if you want really want unit test, you can test this code without Spring - then @RunWith(SpringRunner.class) and @SpringBootTest annotations are not necessary. You can test FooServiceImpl instance. If you have Autowired/injected properties or services, you set them via setters, constructors or mock with Mockito.

提交回复
热议问题