Junit5 测试无法注入依赖项,但 运行 应用程序通常可以注入它

Junit5 Test not able to inject dependency but running application normally can inject it

目前,我在一个项目中工作,我创建了 @Entity Class , @Repository 来存储一些信息。我像其他现有服务一样创建了一个服务,然后尝试将 @Service 注释 class 注入到注释为 @RestController 的控制器中。它运行完美,能够 运行 应用程序正常运行,没有问题,即没有注入问题。

现在,当我尝试 运行 我现有项目的测试时,它失败了,因为我的服务无法注入控制器 class。收到此错误:

No qualifying bean of type 'com.example.service.exampleService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

现在我厌倦了字段和构造函数注入,每次都遇到同样的问题,但我遵循的是项目以前使用的相同模式。我很确定自动装配和其他东西已经正确完成,否则我创建的端点将无法工作。

我的问题是为什么会发生这种情况?即它在 运行ning 作为 spring 启动应用程序但不在测试上下文中时有效。我试图关注其他帖子,但我无法关注它们,因为大多数都是在 Junit4

之前

目前我使用的是Junit5

这是我的测试 classes 的样子

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;


@WebMvcTest
@AutoConfigureMockMvc(addFilters = false)
@ExtendWith(MockitoExtension.class)
public class sampleTest{

 @Test
    public void sampletesting() throws Exception{
      ...
    }
}

这是我正在使用的依赖项和 Spring 引导版本:

    plugins {
        id 'org.springframework.boot' version '2.3.0.RELEASE'
        id 'io.spring.dependency-management' version '1.0.9.RELEASE'
        id 'java'
        id 'jacoco'
    }
 testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    testImplementation('org.mockito:mockito-core:3.5.13')
    testImplementation('org.mockito:mockito-inline:3.5.13')
    testImplementation('org.mockito:mockito-junit-jupiter:3.5.13')

我正在使用 Java 11

@WebMvcTest 用于您只想加载应用程序中所有可用 bean 的特定部分的情况:web 控制器(以及一些其他与 web-mvc 相关的 类,例如转换器, ETC)。它不会加载任何服务,这是故意完成的:

使用@WebMvcTest 意味着您要测试控制器代码(所有注释都已正确定义等)。通常在这种测试中,您将调用控制器方法,使用名为 mockMvc 的东西,并将检查预期结果

您可以阅读 here for example 了解此类测试。通常控制器会注入服务,在这种情况下,您应该在服务上使用 @MockBean

所以严格来说这是失败的原因。

现在在你的情况下,如果你想加载整个应用程序上下文,请考虑使用 @SpringBootTest。您还必须考虑在测试期间应该可以访问的数据库。