java - 为什么在 junit5 测试中 Autowiring 的 Controller 总是为空?

标签 java spring spring-boot maven junit5

我正在尝试向我的应用程序添加一些单元测试(使用 JUnit5 )。但试图 autowire Controller 引发 断言错误 因为 Controller 为空。
测试类:

package com.mydomain.preview.web;
import static org.assertj.core.api.Assertions.assertThat;

import com.mydomain.preview.web.rest.TestController;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class Test1 {

    @Autowired
    private TestController controller;

    @Test
    public void testContext() throws Exception {
    assertThat(controller).isNotNull();
    }

}
Controller 类:
package com.mydomain.preview.web.rest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {

    @RequestMapping
    public @ResponseBody String greeting() {
        return "Hello World";
    }
}
pom.xml(为简洁起见省略了不相关的部分):
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <!-- junit 5 -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <scope>test</scope>
    </dependency>
我遵循了本指南:https://spring.io/guides/gs/testing-web/
我得到的错误是:java.lang.AssertionError: Expecting actual not to be null . mvn test 引发了相同的错误, ./mvnw test并从 IntelliJ IDEA IDE 运行测试。
SpringBootApplication Class:

@SpringBootApplication
@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class})
public class MyApp {

    private static final Logger log = LoggerFactory.getLogger(MyApp.class);

    private final Environment env;

    public MyApp(Environment env) {
        this.env = env;
    }

    @PostConstruct
    public void initApplication() {
        Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
        if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
            log.error("You have misconfigured your application! It should not run " +
                "with both the 'dev' and 'prod' profiles at the same time.");
        }
        if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
            log.error("You have misconfigured your application! It should not " +
                "run with both the 'dev' and 'cloud' profiles at the same time.");
        }
    }

    /**
     * Main method, used to run the application.
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApp.class);
        DefaultProfileUtil.addDefaultProfile(app);
        Environment env = app.run(args).getEnvironment();
        logApplicationStartup(env);
    }

    private static void logApplicationStartup(Environment env) {
        String protocol = "http";
        if (env.getProperty("server.ssl.key-store") != null) {
            protocol = "https";
        }
        String serverPort = env.getProperty("server.port");
        String contextPath = env.getProperty("server.servlet.context-path");
        if (StringUtils.isBlank(contextPath)) {
            contextPath = "/";
        }
        String hostAddress = "localhost";
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            log.warn("The host name could not be determined, using `localhost` as fallback");
        }
        log.info("\n----------------------------------------------------------\n\t" +
                "Application '{}' is running! Access URLs:\n\t" +
                "Local: \t\t{}://localhost:{}{}\n\t" +
                "External: \t{}://{}:{}{}\n\t" +
                "Profile(s): \t{}\n----------------------------------------------------------",
            env.getProperty("spring.application.name"),
            protocol,
            serverPort,
            contextPath,
            protocol,
            hostAddress,
            serverPort,
            contextPath,
            env.getActiveProfiles());
    }
}

最佳答案

我假设 @SpringBootTest 没有找到需要测试的类。尝试添加 @SpringBootTest(classes = {TestController.class})

关于java - 为什么在 junit5 测试中 Autowiring 的 Controller 总是为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62871584/

相关文章:

java - 如何将 Spring Boot 执行器添加到 WAR 项目

java - 如何将原始 HTML 从 java spring Controller 传递到 jsp View

java - 为什么 Java 不优化 String.split ("regex") 对字符串文字的调用?

Spring 安全: authorize on two or more web applications simultaneously

java - Spring MVC - 没有在 JSP View 中获得值(value)

java - Spring Boot @Scheduled 是同步还是异步?

java - 如何随机生成 1 到 50 之间的整数 (java)

java - 如何使用 Java 对 MongoDB 中的文档进行批量更新?

java - Spring boot : Managing bean scope "manually" for dynamically creating beans at runtime with differing states. 我们的解决方案有问题吗?

java - 在 Windows 服务器中运行可执行 jar