ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

UT 上手实践

2021-12-22 10:33:17  阅读:160  来源: 互联网

标签:UT void 实践 jupiter import Test org junit


UT 上手实践

基本工具

Tools

  • Junit——Java主流单元测试框架

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

JUnit Platform:测试框架基础,定义了TestEngine用于开发在平台上运行的测试框架的API。
JUnit Jupiter:JUnit5的核心,是一个基于JUnit Platform的引擎实现,它包含许多丰富的新特性来使得自动化测试更加方便和强大。
JUnit Vintage:兼容JUnit3、JUnit4版本的测试引擎,使得旧版本的自动化测试也可以在JUnit5下正常运行。

  • Mockito——Java单元测试Mock框架

Annotations

注解描述
@Test测试方法
@DisplayName自定义显示名称
@BeforeAll在所有单元测试方法执行之前执行一遍
@BeforeEach在每个单元测试方法执行前都执行一遍
@AfterEach在每个单元测试方法执行后都执行一遍
@AfterAll在所有单元测试方法执行之后执行一遍
@Tag类或方法上声明的标签,用于过滤测试
@Disabled禁用测试类或测试方法
@Timeout执行超过给定的时间,则测试失败。
@ParameterizedTest参数化测试

Assertions


import lombok.AllArgsConstructor;
import lombok.Data;
import org.junit.jupiter.api.Test;

import static java.time.Duration.ofMillis;
import static java.time.Duration.ofMinutes;
import static org.junit.jupiter.api.Assertions.*;

/**
 * AssertionDemoTest
 *
 * @author yuan
 * @since 2021/12/1 09:21
 */
public class AssertionDemoTest {

	private final Calculator calculator = new Calculator();

	private final Person person = new Person("Jane", "Doe");

	@Test
	void standardAssertions() {
		assertEquals(2, calculator.add(1, 1));
		assertEquals(4, calculator.multiply(2, 2),
			"The optional failure message is now the last parameter");
		assertTrue('a' < 'b', () -> "Assertion messages can be lazily evaluated -- "
			+ "to avoid constructing complex messages unnecessarily.");
	}

	@Test
	void groupedAssertions() {
		// In a grouped assertion all assertions are executed, and all
		// failures will be reported together.
		assertAll("person",
			() -> assertEquals("Jane", person.getFirstName()),
			() -> assertEquals("Doe", person.getLastName())
		);
	}

	@Test
	void dependentAssertions() {
		// Within a code block, if an assertion fails the
		// subsequent code in the same block will be skipped.
		assertAll("properties",
			() -> {
				String firstName = person.getFirstName();
				assertNotNull(firstName);

				// Executed only if the previous assertion is valid.
				assertAll("first name",
					() -> assertTrue(firstName.startsWith("J")),
					() -> assertTrue(firstName.endsWith("e"))
				);
			},
			() -> {
				// Grouped assertion, so processed independently
				// of results of first name assertions.
				String lastName = person.getLastName();
				assertNotNull(lastName);

				// Executed only if the previous assertion is valid.
				assertAll("last name",
					() -> assertTrue(lastName.startsWith("D")),
					() -> assertTrue(lastName.endsWith("e"))
				);
			}
		);
	}

	@Test
	void exceptionTesting() {
		Exception exception = assertThrows(ArithmeticException.class, () ->
			calculator.divide(1, 0));
		assertEquals("/ by zero", exception.getMessage());
	}

	@Test
	void timeoutNotExceeded() {
		// The following assertion succeeds.
		assertTimeout(ofMinutes(2), () -> {
			// Perform task that takes less than 2 minutes.
		});
	}

	@Test
	void timeoutNotExceededWithResult() {
		// The following assertion succeeds, and returns the supplied object.
		String actualResult = assertTimeout(ofMinutes(2), () -> {
			return "a result";
		});
		assertEquals("a result", actualResult);
	}

	@Test
	void timeoutNotExceededWithMethod() {
		// The following assertion invokes a method reference and returns an object.
		String actualGreeting = assertTimeout(ofMinutes(2), AssertionDemoTest::greeting);
		assertEquals("Hello, World!", actualGreeting);
	}

	@Test
	void timeoutExceeded() {
		// The following assertion fails with an error message similar to:
		// execution exceeded timeout of 10 ms by 91 ms
		// 超时-任务执行完毕
		assertTimeout(ofMillis(10), () -> {
			// Simulate task that takes more than 10 ms.
			Thread.sleep(100);
		});
	}

	@Test
	void timeoutExceededWithPreemptiveTermination() {
		// The following assertion fails with an error message similar to:
		// execution timed out after 10 ms
		// 超时-则取消任务
		assertTimeoutPreemptively(ofMillis(10), () -> {
			// Simulate task that takes more than 10 ms.
			Thread.sleep(100);
		});
	}

	private static String greeting() {
		return "Hello, World!";
	}


	public static class Calculator {
		public int add(int a, int b) {
			return a + b;
		}

		public int multiply(int a, int b) {
			return a * b;
		}

		public int divide(int a, int b) {
			return a / b;
		}
	}


	@Data
	@AllArgsConstructor
	public static class Person {
		private String firstName;
		private String lastName;
	}
}

小试牛刀

FirstTest

import org.junit.jupiter.api.*;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * FirstTest
 *
 * @author yuan
 * @since 2021/11/29 10:22
 */

public class FirstTest {
  private final Calculator calculator = new Calculator();

  @Test
  @Tag("fast")
  @DisplayName("My 1st JUnit 5 test! 

标签:UT,void,实践,jupiter,import,Test,org,junit
来源: https://blog.csdn.net/fgszdgbzdb/article/details/121662015

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有