当前位置: 首页 > 知识库问答 >
问题:

为什么组件扫描对Spring Boot单元测试不起作用?

胡劲
2023-03-14

服务类fooServiceImpl用@service(又名@component注释,这使它有资格进行自动连接。为什么在单元测试过程中这个类没有被提取和自动连线?

@Service
public class FooServiceImpl implements FooService {
    @Override
    public String reverse(String bar) {
        return new StringBuilder(bar).reverse().toString();
    }
}

@RunWith(SpringRunner.class)
//@SpringBootTest
public class FooServiceTest {
    @Autowired
    private FooService fooService;
    @Test
    public void reverseStringShouldReverseAnyString() {
        String reverse = fooService.reverse("hello");
        assertThat(reverse).isEqualTo("olleh");
    }
}
2018-02-08T10:58:42,385 INFO    Neither @ContextConfiguration nor @ContextHierarchy found for test class [io.github.thenilesh.service.impl.FooServiceTest], using DelegatingSmartContextLoader
2018-02-08T10:58:42,393 INFO    Could not detect default resource locations for test class [io.github.thenilesh.service.impl.FooServiceTest]: no resource found for suffixes {-context.xml}.
2018-02-08T10:58:42,394 INFO    Could not detect default configuration classes for test class [io.github.thenilesh.service.impl.FooServiceTest]: FooServiceTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
2018-02-08T10:58:42,432 INFO    Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, (...)org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
2018-02-08T10:58:42,448 INFO    Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@f0ea28, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@16efaab,(...)org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@9604d9]
2018-02-08T10:58:42,521 INFO    Refreshing org.springframework.context.support.GenericApplicationContext@173f9fc: startup date [Thu Feb 08 10:58:42 IST 2018]; root of context hierarchy
2018-02-08T10:58:42,606 INFO    JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-02-08T10:58:42,666 ERROR    Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@19aaa5] to prepare test instance [io.github.thenilesh.service.impl.FooServiceTest@57f43]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'io.github.thenilesh.service.impl.FooServiceTest': Unsatisfied dependency expressed through field 'fooService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.github.thenilesh.service.FooService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    . . . 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:?]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'io.github.thenilesh.service.FooService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    ... 28 more
2018-02-08T10:58:42,698 INFO    Closing org.springframework.context.support.GenericApplicationContext@173f9fc: startup date [Thu Feb 08 10:58:42 IST 2018]; root of context hierarchy

全堆栈跟踪

如果test class用@SpringBootTest进行了注释,那么它将创建整个应用程序上下文,包括数据库连接和许多不相关的bean,而这些bean显然不需要用于这个单元测试(那么它就不是单元测试了!)。希望只有fooservice所依赖的bean才应该被实例化,但使用@mockbean进行模拟的bean除外。

共有1个答案

蒲昀
2023-03-14

您应该使用@springboottest(classes=fooServiceImpl.class)

正如它在注释类型SpringBootTest上提到的:

公共抽象类[]类

这将只加载必要的类。如果不指定,它可能会加载数据库配置和其他东西,这会使您的测试更慢。

另一方面,如果您确实想要单元测试,您可以在没有Spring的情况下测试此代码--那么@runwith(SpringRunner.class)@springboottest注释就不是必需的。您可以测试fooServiceimpl实例。如果您有autowired/injected属性或服务,您可以通过setter、constructors或mock使用mockito来设置它们。

 类似资料:
  • 我正在尝试使用Mockito在SprinBoot应用程序中进行一些jUnit测试。 现在我的服务有了一些变量,可以从通过注释: 我试图通过像这样使用来测试这个: 但是,该属性不会被填充,并保持为。 这方面有很多TPOIC,但我还没能拼凑出一个解决方案。我看到解决方案建议,但它似乎想做一个集成测试,使服务加速,但由于无法连接到数据库,服务失败了。所以这不是我想要的。 我还看到一些解决方案建议我制作一

  • 我正在使用一个带有spring boot 2.0.0.rc1的多项目分级器。我的子项目之一是SpringBoot应用程序,其中包含了我的集成测试。 集成测试用WebEnvironment.random_port标记为@springboottest。由于未解析的依赖关系(在另一个子项目中声明的服务,的同级),测试失败,使用了gradle命令行,但在Eclipse IDE中成功。 如果有人有主意?如何

  • 因此,我是一个新的Java程序员,我正试图弄清楚为什么一段代码不能工作。我遇到的问题是“String interests=input.nextLine();”这一行,它跳过了用户的输入并跳转到下一个System.out,所以它只显示“Your Profile...”。在允许用户输入任何数据之前。抱歉,如果这是一个愚蠢的问题,我是很新的!

  • 问题内容: 当我使用jdk 7运行Json测试程序时,它说: 我在项目中包含了“ javax.json-api-1.0.jar”。 这是一个简单的程序,没有使用galssfish,为什么在这里提到玻璃鱼? 问题答案: 仅包含用于编译时依赖的API。但是,如果要运行您的应用程序,则需要一个类。 是您需要的同时包含+ 类的jar 。 有关更多详细信息,请参见此线程。

  • 问题内容: 因此,我是一名新Java程序员,我试图弄清楚为什么一段代码无法正常工作。我遇到的问题是:“字符串兴趣= input.nextLine();”,它跳过了用户的输入并跳至下一个System.out,因此它仅在控制台中显示“您的个人资料…”在允许用户输入任何数据之前。抱歉,这是一个愚蠢的问题,我很新! 问题答案: 这样说: 其余代码可能与您上面的代码相同。 编辑: 它必须是这样的(我的意思是

  • 我创建了一个示例Spring Boot应用程序,当所有服务类都在一个包中时,该应用程序运行良好,但如果一个服务类引用了不同包中的另一个服务类,那么我将得到BeanCreationException 下面给出了应用程序的代码