Почему контроллер @Autowired всегда имеет значение null в тесте Junit5? - PullRequest
0 голосов
/ 13 июля 2020

Я пытаюсь добавить несколько тестов Junit 5 в свое приложение. Но когда я пытаюсь использовать @Autowire для контроллера, он терпит неудачу, потому что контроллер имеет значение null.

Test:

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.

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

Ответы [ 2 ]

2 голосов
/ 13 июля 2020

Я предполагаю, что @SpringBootTest не находит классы, которые нужно протестировать. Попробуйте добавить @SpringBootTest(classes = {TestController.class})

0 голосов
/ 13 июля 2020

Я пробовал это локально, и он работает ...

Единственное, что я обнаружил, что не имело смысла, это то, что assertThat(controller).isNotNull(); принимает два аргумента. Попробуйте вместо этого assertNotNull(controller)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...