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

使用JUnit 5进行Maven测试时出错

康照
2023-03-14
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.datastech</groupId>
    <artifactId>cra</artifactId>
    <version>0.0.1</version>
    <packaging>pom</packaging>
    <modules>
        <module>core</module>
        <module>internal</module>
        <module>external</module>
    </modules>

    <name>cra</name>
    <description>CRA connector for Oschadbank</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/>
    </parent>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <lombok.version>1.16.20</lombok.version>
        <elasticsearch.version>6.2.4</elasticsearch.version>

        <junit.jupiter.version>5.2.0</junit.jupiter.version>
        <junit.platform.version>1.0.3</junit.platform.version>

        <!-- Environment variable -->
        <!-- TODO добавить пользователя для БКИ коннекторов -->
        <mongo.uri>resourceServer:sjv99gKm@192.168.3.43:27017,192.168.3.70:27017</mongo.uri>

        <elasticsearch.host>192.168.3.43</elasticsearch.host>
        <elasticsearch.port>9200</elasticsearch.port>

        <ldap.url>ldap://192.168.3.90:389</ldap.url>
        <ldap.base>DC=contoso,DC=local</ldap.base>
        <ldap.user>CN=Artur,CN=Users,DC=contoso,DC=local</ldap.user>
        <ldap.password>zaq1@WSX</ldap.password>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-ldap</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>
         <!--<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <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>
        <dependency>
            <groupId>de.flapdoodle.embed</groupId>
            <artifactId>de.flapdoodle.embed.mongo</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-mockmvc</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- AOP -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!-- AOP -->

        <!-- Util dependencies -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
            <optional>true</optional>
        </dependency>
        <!-- Util dependencies -->

        <!-- Elasticsearch -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <!-- Elasticsearch -->

        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast-spring</artifactId>
        </dependency>

        <!-- JUnit 5 -->
        <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter-api</artifactId>
                <version>${junit.jupiter.version}</version>
                <scope>test</scope>
            </dependency>
          <dependency>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
            <version>5.2.0</version>
            <scope>test</scope>
        </dependency>

        <!-- JUnit 5 -->


    </dependencies>

    <build>
        <plugins>
            <!--  Checkstyle -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-checkstyle-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <configLocation>checks.xml</configLocation>
                </configuration>
                <executions>
                    <execution>
                        <id>checkstyle</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>check</goal>
                        </goals>
                        <configuration>
                            <failOnViolation>true</failOnViolation>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!--  Checkstyle -->

            <!-- Static code analysis -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-pmd-plugin</artifactId>
                <version>3.9.0</version>
                <configuration>
                    <targetJdk>9</targetJdk>
                    <failOnViolation>true</failOnViolation>
                    <printFailingErrors>true</printFailingErrors>
                    <linkXRef>false</linkXRef>
                    <analysisCache>true</analysisCache> <!-- enable incremental analysis -->
                    <minimumTokens>100</minimumTokens> <!-- minimum code size which trips the CPD -->
                    <rulesets>
                        <!-- A rule set, that comes bundled with PMD -->
                        <ruleset>/category/java/bestpractices.xml</ruleset>
                    </rulesets>
                </configuration>
                <executions>
                    <execution>
                        <phase>test</phase>
                        <goals>
                            <goal>check</goal>
                            <goal>cpd-check</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <!-- Static code analysis -->

            <!-- Runs the unit tests -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <dependencies>
                    <dependency>
                        <groupId>org.junit.platform</groupId>
                        <artifactId>junit-platform-surefire-provider</artifactId>
                        <version>${junit.platform.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.junit.jupiter</groupId>
                        <artifactId>junit-jupiter-engine</artifactId>
                        <version>${junit.jupiter.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <failIfNoTests>true</failIfNoTests>
                </configuration>
            </plugin>
            <!-- Runs the unit tests -->

        </plugins>
    </build>

</project>
@Service
@Profile("!local")
public class CraConfigurationServiceProduction implements CraConfigurationService {

    private static final String SERVICE_NAME = "CraConfigurationService";

    /**
     * Шаблон адреса сервиса поиска конфигурации коннектора БКИ
     */
    private final String internalModuleUrl;

    /**
     * REST Template для взаимодействия с внутренним модулем
     */
    private final RestTemplate restTemplate;

    /**
     * Репозиторий с настройками подключения к БКИ в распределенном кеше
     */
    private final CraConfigImdgRepository craConfigImdgRepository;

    /**
     * Сервис логирования
     */
    private final ElasticsearchService logService;

    public CraConfigurationServiceProduction(RestTemplate restTemplate,
                                             @Value("${system.url.internal}") final String internalUrl,
                                             CraConfigImdgRepository craConfigImdgRepository,
                                             ElasticsearchService logService) {
        this.restTemplate = restTemplate;
        internalModuleUrl = internalUrl + "internal/api/cra/configs/{name}";
        this.craConfigImdgRepository = craConfigImdgRepository;
        this.logService = logService;
    }

    @Override
    public Optional<CraConfigImdg> getConfiguration(String craName) {
        CraConfigImdg result = craConfigImdgRepository.getCraConfigByName(craName);

        if (result == null) {
            GenericResponse<CraConfigDto> response;

            try {
                response = restTemplate.exchange(internalModuleUrl, HttpMethod.GET, null,
                        new ParameterizedTypeReference<GenericResponse<CraConfigDto>>() {
                        }, craName).getBody();
            } catch (Exception e) {
                // TODO Добавить логирование
                return Optional.empty();
            }

            if (response == null || response.getData() == null) {
                return Optional.empty();
            } else {
                CraConfigImdg craConfigImdg = new CraConfigImdg(response.getData());
                updateConfiguration(craConfigImdg);
                return Optional.of(craConfigImdg);
            }
        } else {
            return Optional.of(result);
        }
    }
}
public class CraConfigurationServiceProductionTest extends AbstractSpringTest {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${system.url.internal}")
    private String internalUrl;

    @Autowired
    private CraConfigImdgRepository craConfigImdgRepository;

    @Autowired
    private ElasticsearchService logService;

    private CraConfigurationService craConfigurationService;

    private MockRestServiceServer mockServer;

    private String serviceUrl;

    @BeforeEach
    public void setUp() {
        craConfigurationService = new CraConfigurationServiceProduction(restTemplate,
                internalUrl, craConfigImdgRepository, logService);
        mockServer = MockRestServiceServer.createServer(restTemplate);
        serviceUrl = internalUrl + "internal/api/cra/configs/";
    }

    @Test
    public void getConfigurationSuccessful() throws Exception {
        String craConfigResponse = loadResourceAsString("responses/internal/get-cra-configuration-successful.json");

        mockServer
                .expect(requestTo(serviceUrl + "kyivstar"))
                .andExpect(method(HttpMethod.GET))
                .andRespond(withSuccess(craConfigResponse, MediaType.APPLICATION_JSON));

        Optional<CraConfigImdg> response = craConfigurationService.getConfiguration("kyivstar");
        mockServer.verify();

        assertThat(response.isPresent()).isTrue();

        CraConfigImdg craConfigImdg = response.orElse(null);

        assertThat(craConfigImdg).isNotNull();
        assertThat(craConfigImdg.getName()).isNotNull().isEqualTo("kyivstar");
        assertThat(craConfigImdg.getUrl()).isNotNull().isEqualTo("https://scoring.kyivstar.ua/rest/api/v1/scoring");
        assertThat(craConfigImdg.getUser()).isNotNull().isEqualTo("user");
        assertThat(craConfigImdg.getPassword()).isNotNull().isEqualTo("password");

        mockServer.reset();
    }
}
Failed tests: CraConfigurationServiceProductionTest.getConfigurationSuccessful:67 Further request(s) expected leaving 1 unsatisfied expectation(s).
0 request(s) executed.

问题出现在mockserver.verify();字段中。

在JUnit4中,一切都工作得很好,没有错误。我试图使用JUnit4中的@test,因为我在pom.xml中有一个junit-vintage-engine依赖项,但没有帮助。

共有1个答案

宋明亮
2023-03-14

根据JUnit官方文档,JUnit5和IntelliJ IDEA之间存在一些不兼容之处。他们建议使用IntelliJ IDEA 2017.3或更新版本。

我甚至在2018.1版本中遇到了一些问题,它通过推荐的额外Maven依赖项得到了解决。我还必须像其他人一样将junit-jupiter-api依赖项版本设置为5.2.0。

使用Maven构建支持一节对于配置maven-surefire-plugin非常有用。

 类似资料:
  • 我遇到了无法使用Maven运行JUnit5测试的问题。在IDE中运行它们工作正常,但使用“mvn测试”会产生以下输出: 这是我的测试课程: pom: 我做了一些研究,我认为这可能与混合JUnit4和JUnit5特性有关,这导致maven surefire插件无法运行测试。然而,我找不到那些剩余的JUnit4特性可能在哪里。我将感谢任何帮助。

  • 我发现Junit5从5.3版本开始就支持并行性,但我找不到任何关于如何使用csv源代码运行并行测试的参考。你有什么建议吗?

  • Maven执行 问题-这个自定义提供程序是否不再受支持,或者是否有任何解决方案可以使用、和/或执行测试? 注意-测试执行在JUnit-4中运行良好。

  • Gradle4.6增加了对JUnit5的支持。 只要我没有用于例如集成测试的另一个sourceset,这对我是有效的:我不知道如何在我的集成测试中启用。 我所能做的是让任务与新的JUnit5支持一起工作,但我的任务使用JUnit5控制台并从命令行运行测试。最后,我在gradle中放弃对JUnit5的支持,并回滚到使用JUnit5控制台进行两个测试。 除了之外,如何在其他任务上启用Gradle4.6

  • 问题内容: Maven执行 我正在尝试使用我的一个Maven项目,但在此阶段无法使用- 我得到的输出是- 尝试实施上述解决方案@ Surefire没有采用Junit5测试来将依赖关系更新为- 并将插件更新为- 但输出保持不变。 问题 -这是自定义提供没有更多的支持,或者是有什么解决方案使用执行测试,和/或 现在? 注意 -测试执行在JUnit-4上运行良好。 问题答案: 您应该像这样配置maven

  • 我试图测试一个基于Spring引导的Restendpoint。代码能够返回预期的输出,但测试失败,错误如下: 已解析[org.springframework.http.converter.HttpMessageNotWritableException:预设内容类型为“null”的[class java.util.LinkedList]没有转换器 对此有任何想法都将不胜感激! 下面是相同的代码: 控