【问题标题】:Why is an autowired controller always null in junit5 tests?为什么在 junit5 测试中自动连线控制器总是为空?
【发布时间】:2020-11-02 09:31:26
【问题描述】:

我正在尝试向我的应用程序添加一些单元测试(使用 JUnit5)。但尝试autowire controller 会引发assertion error,因为控制器为空。

测试类:

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();
    }

}

控制器类:

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());
    }
}

【问题讨论】:

  • 请在 github 等上创建一个示例项目。
  • 如何启动应用程序?你能显示用@SpringBootApplication注释的类吗?
  • @user991710 已将代码添加到问题中。

标签: java spring spring-boot maven junit5


【解决方案1】:

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

【讨论】:

  • 我试过了,可惜没有解决问题。
  • 添加后是否进行了 mvn clean install?
【解决方案2】:

我在本地尝试过,它可以工作......

我发现唯一没有意义的是assertThat(controller).isNotNull(); 有两个参数。试试assertNotNull(controller)

【讨论】:

  • 他正在使用 org.assertj.core.api.Assertions.assertThat。
  • 你还有@RequestMapping吗?这是对我来说测试失败的另一件事。没有明确端点的 2 个控制器(或更多)导致了冲突。
  • 你在依赖项中有 spring-boot-starter-web 因为这是 @RequestMapping 依赖项的来源
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-05
  • 1970-01-01
  • 2021-06-16
  • 2023-03-05
  • 2012-02-27
  • 2016-11-07
相关资源
最近更新 更多