您当前的位置: 首页 >  单元测试

liaowenxiong

暂无认证

  • 5浏览

    0关注

    1171博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Maven的单元测试没有执行的问题

liaowenxiong 发布时间:2022-01-28 19:12:28 ,浏览量:5

今天使用 Maven 的单元测试,正常导入以下的类

org.junit.Assert;
org.junit.After;
org.junit.Before;
org.junit.Test;

在项目的根目录下执行 mvn test,结果并没有执行单元测试,也是无语了。普通的 Java 项目可以正常运行,但是 Maven Web Java 工程,通过 mvn test 命令却无法成功执行测试用例。

后来网络上查看了资料,maven-surefire-plugin 不支持以前的 Test 注解了,需要依赖 junit-jupiter-api:5.7.0,使用里面的测试注解。

具体区别如下:

注解位于 org.junit.jupiter.api 包中。

断言位于 org.junit.jupiter.api.Assertions 类中。

假设位于 org.junit.jupiter.api.Assumptions 类中。

@Before@After 不再存在;使用 @BeforeEach@AfterEach

@BeforeClass@AfterClass 不再存在;使用 @BeforeAll@AfterAll

@Ignore 不再存在;使用 @Disabled

@Category 不再存在;使用 @Tag

@RunWith 不再存在;使用 @ExtendWith

@Rule@ClassRule 不再存在;使用 @ExtendWith@RegisterExtension

所以测试用例如下所示,导入 org.junit.jupiter.api 包下的类和注解,不要导入 org.junit 包下的类和注解:

package com.example.demo02;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/**
 * description
 *
 * @author liaowenxiong
 * @date 2022/1/28 08:18
 */

public class HelloMavenTest {
  private HelloMaven hm;

  @BeforeEach
  public void setUp() {
    hm = new HelloMaven();
  }

  @Test
  public void testAdd() throws InterruptedException {
    int a = 1;
    int b = 2;
    int result = hm.add(a, b);
    Assertions.assertEquals(a + b, result);
  }

  @Test
  public void testSubtract() throws InterruptedException {
    int a = 1;
    int b = 2;
    int result = hm.subtract(a, b);
    Assertions.assertEquals(a - b, result);
  }

  @AfterEach
  public void tearDown() throws Exception {
    System.out.println("测试结束了!");
  }
}

对应的 pom.xml 配置内容:



	4.0.0
	com.example.mvnbook
	hello-world
	1.0-SNAPSHOT
	Maven Hello World Project
	
		
		
			org.junit.jupiter
			junit-jupiter-api
			5.8.2
			test
		
	
	
		
			
				
				
					org.apache.maven.plugins
					maven-surefire-plugin
					3.0.0-M5
				
				
					org.apache.maven.plugins
					maven-compiler-plugin
					
						1.9
						1.9
						UTF-8
					
				
			
		
	

关注
打赏
1661566967
查看更多评论
立即登录/注册

微信扫码登录

0.1099s