mvn test命令在Spring Boot项目中无法运行测试

5

这是我的pom文件

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ricardo</groupId>
    <artifactId>cdh</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>cdh</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <azure.version>2.2.0</azure.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</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-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
            <version>2.0.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-core</artifactId>
            <version>2.3.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.1.44</version>
        </dependency>

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-core</artifactId>
            <version>1.1.44</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>2.3.6</version>
        </dependency>

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-storage</artifactId>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20190722</version>
        </dependency>

        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-security-keyvault-secrets</artifactId>
            <version>4.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-identity</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-eventhubs</artifactId>
            <version>2.3.0</version>
        </dependency>

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.microsoft.azure</groupId>
                <artifactId>azure-spring-boot-bom</artifactId>
                <version>${azure.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    <profiles>
        <profile>
            <id>local</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <activatedProperties>local</activatedProperties>
            </properties>
        </profile>
        <profile>
            <id>dev</id>
            <properties>
                <activatedProperties>dev</activatedProperties>
            </properties>
        </profile>
        <profile>
            <id>test</id>
            <properties>
                <activatedProperties>test</activatedProperties>
            </properties>
        </profile>
    </profiles>
</project>

当我运行mvn test命令时,输出如下,并且没有测试被执行。然而在使用Intellij IDE中,每个测试都按预期工作。
[INFO] Building cdh 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ cdh ---
[INFO] Deleting /Users/ricardochampa/mypath/target
[INFO] 
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 4 resources
[INFO] Copying 4 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ cdh ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 140 source files to /Users/mypath/cdh-back/target/classes
[INFO] /Users/mypath/cdh-back/src/main/java/com/ricardo/cdh/mappers/OrdersMapper.java: Some input files use unchecked or unsafe operations.
[INFO] /Users/mypath/cdh-back/src/main/java/com/ricardo/cdh/mappers/OrdersMapper.java: Recompile with -Xlint:unchecked for details.
[INFO] 
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/mypath/cdh-back/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ cdh ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 6 source files to /Users/mypath/cdh-back/target/test-classes
[INFO] 
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ cdh ---
[INFO] 


[INFO] -------------------------< com.ricardo:cdh >--------------------------
[INFO] Building cdh 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 4 resources
[INFO] Copying 4 resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ cdh ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ cdh ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/mypath/cdh-back/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ cdh ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ cdh ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.484 s
[INFO] Finished at: 2020-09-30T22:18:05+02:00
[INFO] ------------------------------------------------------------------------

更新

我刚刚尝试了以下的pom.xml文件

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            <configuration>
                <includes>
                    <include>*Test.java</include>
                </includes>
            </configuration>
        </plugin>
    </plugins>
</build>

我也尝试了这个。

 <build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
            <configuration>
                <includes>
                    <include>customWildcardPattern</include>
                </includes>
            </configuration>
        </plugin>
    </plugins>
</build>

And this...

 <build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
        </plugin>
    </plugins>
</build>

并且这个……

 <build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
        </plugin>
    </plugins>
</build>

他们都不起作用 :(

项目结构。

enter image description here

一个测试类的示例:ProductsServiceTest

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class ProductsServiceTest {
    @Mock ProductsRepository productsRepository;
    @Mock ResourceService resourceService;
    @Autowired @InjectMocks ProductsService service;
    private ProductsEntity productsEntity = new ProductsEntity();
    private final String stubSearchText = "search this text with results";
    private final String stubSearchTextNoResults = "search this text without results";
    private final String notFoundStubID = "ID NOT EXISTS";
    private final String stubID = "id";
    private final String stubName = "name";

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        productsEntity.setId(stubID);
        productsEntity.setName(stubName);
        when(productsRepository.findById(stubID)).thenReturn(Optional.of(productsEntity));
        when(productsRepository.findById(notFoundStubID)).thenReturn(Optional.empty());
        doNothing().when(resourceService).changeResourceStatus(any(String.class), any(String.class));
        List<ProductsEntity> productsEntityList = new ArrayList<>();
        productsEntityList.add(productsEntity);
        when(productsRepository.searchProducts(stubSearchText)).thenReturn(productsEntityList);
    }
    @Test
    public void whenGetProduct() throws CdhException {
        ProductsDto productsDto = service.getProduct(stubID);
        assertEquals(productsDto.getId(), stubID);
        assertEquals(productsDto.getName(), stubName);
    }
    @Test
    public void whenGetProductNotExist() {
        assertThatThrownBy(() -> service.getProduct(notFoundStubID)).isInstanceOf(CdhException.class);
    }
    @Test
    public void whenCreateProduct() {
        ProductsDto dto = new ProductsDto();
        dto.setId("fake id");
        dto.setIdResource("fake id resource");
        service.createProduct(dto);
        verify(service.productsRepository).save(any(ProductsEntity.class));
    }
    @Test
    public void whenDeleteProduct() throws CdhException {
        service.deleteProduct(stubID);
        verify(service.productsRepository).save(any(ProductsEntity.class));
    }

}

如果M.mas提供的解决方案有效,那就太棒了!否则,最好您发布测试包结构以及编写junit的Test类。 - Mayank Madhav
请添加其中一个测试类。 - Katy
完成。添加了一个测试类。 - Ricardo
6个回答

10
我终于解决了它。 我的问题在于JUnit4,根据文档https://maven.apache.org/surefire/maven-surefire-plugin/examples/junit.html,我应该像这样添加插件。
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M5</version>
            <dependencies>
                <dependency>
                    <groupId>org.apache.maven.surefire</groupId>
                    <artifactId>surefire-junit4</artifactId>
                    <version>3.0.0-M5</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

3

1. 可能的第一个根本原因:测试类的命名

确保你的测试类名称与以下默认的 Maven Surefire 插件模式之一相匹配:

  1. Test*.java
  2. *Test.java
  3. *Tests.java
  4. *TestCase.java

如果您需要自定义它,您需要添加:

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M5</version>
        <configuration>
          <includes>
            <include>TO_BE_REPLACED_BY_YOUR_CUSTOM_WILDCARD_PATTERN</include>
          </includes>
        </configuration>
      </plugin>
    </plugins>
  </build>
  [...]
</project>

###更新####:

2. 可能导致测试未执行的第二个潜在根本原因是你的spring-boot-starter-test中的排除部分。

替换为:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

由:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

我已经添加了依赖项,但测试仍然无法运行。我的所有测试类都以Test.java结尾。 - Ricardo

1

关键在于理解Spring使用的测试引擎。

在我的情况下,我使用@RunWith(SpringRunner.class)编写API测试,它位于JUnit4下,运行时使用junit-vintage-engine

但是单元测试是使用JUnit Jupiter编写的,它位于JUnit5下,运行时使用junit-jupiter-engine

SpringBoot的默认引擎是junit-jupiter-engine。因此,我们必须告诉Spring我们也想使用junit-vintage-engine

我们可以在pom.xml中简单地添加依赖项:

<dependency>
  <groupId>org.junit.vintage</groupId>
  <artifactId>junit-vintage-engine</artifactId>
  <scope>test</scope>
</dependency>

或者,如果我们想要使用maven-surefire,我们可以在插件内添加依赖项:

<plugin>
  <groupId>org.apache.maven.plugins</groupId> 
  <artifactId>maven-surefire-plugin</artifactId>
  <version>3.0.0-M7</version>
  <dependencies>
    <dependency>
      <groupId>org.junit.vintage</groupId>
      <artifactId>junit-vintage-engine</artifactId>
      <version>5.7.0</version>
    </dependency>
  </dependencies>
</plugin>

1
我遇到了类似的问题,在我的情况下,我的应用程序上下文中不知何故同时出现了Junit 5和Junit 4的组合。Spring Boot Starter Test正在扫描Junit 5测试,而我的一些旧测试用例则使用了Junit 4的注解。一旦我将这些旧测试用例升级到Junit 5,它们就能在运行Maven测试生命周期事件时被找到。当手动运行每个类型的测试时,两种类型的测试都能正常运行。

1

您的pom.xml文件中缺少maven surefire插件。


2
Spring Boot应该为您提供此插件。 查看日志,您将清楚地看到: [INFO] - maven-surefire-plugin:2.22.2:test (default-test) @ cdh --- - Katy
我刚刚添加了插件2.22.2,但行为仍然相同。测试类没有运行。所有我的测试类都以Test.java结尾。 - Ricardo
尝试使用测试范围添加 junit-jupiter-engine 和 junit-jupiter-api 依赖项。 - Mayank Madhav
请参考以下链接:https://youtu.be/EROuIf2Ac_I - Mayank Madhav

0
请务必使用@Test注释您的测试方法: import org.junit.jupiter.api.Test; // <-- 或者您正在使用的任何其他内容。

public class SomeTest {
  ...

  @Test // <----
  public void testSomething() {
    ...
  }
  ...
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接