# JUnit5 断言示例

> 原文： [https://howtodoinjava.com/junit5/junit-5-assertions-examples/](https://howtodoinjava.com/junit5/junit-5-assertions-examples/)

**JUnit5 断言**帮助用测试用例的实际输出来验证期望的输出。 为简单起见，所有 **JUnit Jupiter 断言**是[`org.junit.jupiter.Assertions`](http://junit.org/junit5/docs/current/api/org/junit/jupiter/api/Assertions.html)类中的静态方法。

```java
Table of Contents

Assertions.assertEquals() and Assertions.assertNotEquals()
Assertions.assertArrayEquals()
Assertions.assertIterableEquals()
Assertions.assertLinesMatch()
Assertions.assertNotNull() and Assertions.assertNull()
Assertions.assertNotSame() and Assertions.assertSame()
Assertions.assertTimeout() and Assertions.assertTimeoutPreemptively()
Assertions.assertTrue() and Assertions.assertFalse()
Assertions.assertThrows()
Assertions.fail()
```

## `Assertions.assertEquals()`和`Assertions.assertNotEquals()`示例

使用`Assertions.assertEquals()`断言**期望值等于实际值**。 `assertEquals()`针对不同的数据类型（例如， `int`，`short`，`float`，`char`等。它还支持传递传递的错误消息，以防万一测试失败。 例如：

```java
public static void assertEquals(int expected, int actual)
public static void assertEquals(int expected, int actual, String message)
public static void assertEquals(int expected, int actual, Supplier<String< messageSupplier)
```

```java
void testCase() 
{
	//Test will pass
	Assertions.assertEquals(4, Calculator.add(2, 2));

	//Test will fail 
	Assertions.assertEquals(3, Calculator.add(2, 2), "Calculator.add(2, 2) test failed");

	//Test will fail 
	Supplier&lt;String&gt; messageSupplier  = ()-> "Calculator.add(2, 2) test failed";
	Assertions.assertEquals(3, Calculator.add(2, 2), messageSupplier);
}

```

类似地，`Assertions.assertNotEquals()`方法用于断言**期望值不等于实际值**。 与`assertEquals()`相比，`assertNotEquals()`不会针对不同的数据类型重载方法，而仅接受`Object`。

```java
public static void assertNotEquals(Object expected, Object actual)
public static void assertNotEquals(Object expected, Object actual, String message)
public static void assertNotEquals(Object expected, Object actual, Supplier<String> messageSupplier)
```

```java
void testCase() 
{
	//Test will pass
	Assertions.assertNotEquals(3, Calculator.add(2, 2));

	//Test will fail 
	Assertions.assertNotEquals(4, Calculator.add(2, 2), "Calculator.add(2, 2) test failed");

	//Test will fail 
	Supplier&lt;String&gt; messageSupplier  = ()-> "Calculator.add(2, 2) test failed";
	Assertions.assertNotEquals(4, Calculator.add(2, 2), messageSupplier);
}

```

## `Assertions.assertArrayEquals()`示例

与`assertEquals()`相似，`assertArrayEquals()`对数组执行相同的操作，即断言**期望数组等于实际数组**。 它还具有针对不同数据类型的重载方法，例如`boolean[]`，`char[]`，`int[]`等。它还支持在测试失败的情况下传递要打印的错误消息。 例如：

```java
public static void assertArrayEquals(int[] expected, int[] actual)
public static void assertArrayEquals(int[] expected, int[] actual, String message)
public static void assertArrayEquals(int[] expected, int[] actual, Supplier<String> messageSupplier)
```

```java
void testCase() 
{
	//Test will pass
	Assertions.assertArrayEquals(new int[]{1,2,3}, new int[]{1,2,3}, "Array Equal Test");

	//Test will fail because element order is different
	Assertions.assertArrayEquals(new int[]{1,2,3}, new int[]{1,3,2}, "Array Equal Test");

	//Test will fail because number of elements are different
	Assertions.assertArrayEquals(new int[]{1,2,3}, new int[]{1,2,3,4}, "Array Equal Test");
}

```

## `Assertions.assertIterableEquals()`示例

它断言**期望和实际的可迭代项高度相等**。 高度相等意味着集合中元素的数量和顺序必须相同； 以及迭代元素必须相等。

它还有 3 种重载方法。

```java
public static void assertIterableEquals(Iterable<?> expected, Iterable> actual)
public static void assertIterableEquals(Iterable<?> expected, Iterable> actual, String message)
public static void assertIterableEquals(Iterable<?> expected, Iterable> actual, Supplier<String> messageSupplier)
```

```java
@Test
void testCase() 
{
	 Iterable<Integer> listOne = new ArrayList<>(Arrays.asList(1,2,3,4));
	 Iterable<Integer> listTwo = new ArrayList<>(Arrays.asList(1,2,3,4));
	 Iterable<Integer> listThree = new ArrayList<>(Arrays.asList(1,2,3));
	 Iterable<Integer> listFour = new ArrayList<>(Arrays.asList(1,2,4,3));

	//Test will pass
	Assertions.assertIterableEquals(listOne, listTwo);

	//Test will fail
	Assertions.assertIterableEquals(listOne, listThree);

	//Test will fail
	Assertions.assertIterableEquals(listOne, listFour);
}

```

## `Assertions.assertLinesMatch()`示例

它断言**期望的字符串列表与实际列表**相匹配。 将一个字符串与另一个字符串匹配的逻辑是：

1.  检查`expected.equals(actual)` –如果是，则继续下一对
2.  否则将`expected`视为正则表达式，并通过
    [`String.matches(String)`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#matches-java.lang.String-) 检查–如果是，则继续下一对
3.  否则检查`expected`行是否为快进标记，如果是，则相应地应用
    快速前行并转到 1。

有效的快进标记是以`>>`开头和结尾并且至少包含 4 个字符的字符串。 快进文字之间的任何字符都将被丢弃。

```java
>>>>
>> stacktrace >>
>> single line, non Integer.parse()-able comment >>

```

## `Assertions.assertNotNull()`和`Assertions.assertNull()`示例

`assertNotNull()`断言**实际值不为空**。 类似地，`assertNull()`方法断言**实际值为空**。 两者都有三种重载方法。

```java
public static void assertNotNull(Object actual)
public static void assertNotNull(Object actual, String message)
public static void assertNotNull(Object actual, Supplier<String> messageSupplier)

public static void assertEquals(Object actual)
public static void assertEquals(Object actual, String message)
public static void assertEquals(Object actual, Supplier<String> messageSupplier)
```

```java
@Test
void testCase() 
{	 
	String nullString = null;
	String notNullString = "howtodoinjava.com";

	//Test will pass
	Assertions.assertNotNull(notNullString);

	//Test will fail
	Assertions.assertNotNull(nullString);

	//Test will pass
	Assertions.assertNull(nullString);

	// Test will fail
	Assertions.assertNull(notNullString);
}

```

## `Assertions.assertNotSame()`和`Assertions.assertSame()`示例

`assertNotSame()`断言**预期和实际不引用同一对象**。 同样，`assertSame()`方法断言，**预期和实际引用完全相同的对象**。 两者都有三种重载方法。

```java
public static void assertNotSame(Object actual)
public static void assertNotSame(Object actual, String message)
public static void assertNotSame(Object actual, Supplier<> messageSupplier)

public static void assertSame(Object actual)
public static void assertSame(Object actual, String message)
public static void assertSame(Object actual, Supplier<String> messageSupplier)
```

```java
@Test
void testCase() 
{	 
	String originalObject = "howtodoinjava.com";
	String cloneObject = originalObject;
	String otherObject = "example.com";

	//Test will pass
	Assertions.assertNotSame(originalObject, otherObject);

	//Test will fail
	Assertions.assertNotSame(originalObject, cloneObject);

	//Test will pass
	Assertions.assertSame(originalObject, cloneObject);

	// Test will fail
	Assertions.assertSame(originalObject, otherObject);
}

```

## `Assertions.assertTimeout()`和`Assertions.assertTimeoutPreemptively()`示例

`assertTimeout()`和`assertTimeoutPreemptively()`均用于测试长时间运行的任务。 如果测试用例中的给定任务花费的时间超过指定的持续时间，则测试将失败。

两种方法之间唯一的区别是`assertTimeoutPreemptively()`中的设置，如果超过超时，`Executable`或`ThrowingSupplier`的执行将被抢先中止。 在`assertTimeout()`的情况下，不会中断`Executable`或`ThrowingSupplier`。

```java
public static void assertTimeout(Duration timeout, Executable executable)
public static void assertTimeout(Duration timeout, Executable executable, String message)
public static void assertTimeout(Duration timeout, Executable executable, Supplier<String> messageSupplier)
public static void assertTimeout(Duration timeout, ThrowingSupplier<T> supplier, String message)
public static void assertTimeout(Duration timeout, ThrowingSupplier<T> supplier, Supplier<String> messageSupplier)
```

```java
@Test
void testCase() {

	//This will pass
	Assertions.assertTimeout(Duration.ofMinutes(1), () -> {
		return "result";
	});

	//This will fail
	Assertions.assertTimeout(Duration.ofMillis(100), () -> {
		Thread.sleep(200);
		return "result";
	});

	//This will fail
	Assertions.assertTimeoutPreemptively(Duration.ofMillis(100), () -> {
		Thread.sleep(200);
		return "result";
	});
}

```

## `Assertions.assertTrue()`和`Assertions.assertFalse()`示例

`assertTrue()`断言`BooleanSupplier`提供的条件为真。 类似地，`assertFalse()`断言**提供的条件为假**。 它具有以下重载方法：

```java
public static void assertTrue(boolean condition)
public static void assertTrue(boolean condition, String message)
public static void assertTrue(boolean condition, Supplier<String> messageSupplier)
public static void assertTrue(BooleanSupplier booleanSupplier)
public static void assertTrue(BooleanSupplier booleanSupplier, String message)
public static void assertTrue(BooleanSupplier booleanSupplier, Supplier<String> messageSupplier)

public static void assertFalse(boolean condition)
public static void assertFalse(boolean condition, String message)
public static void assertFalse(boolean condition, Supplier<String> messageSupplier)
public static void assertFalse(BooleanSupplier booleanSupplier)
public static void assertFalse(BooleanSupplier booleanSupplier, String message)
public static void assertFalse(BooleanSupplier booleanSupplier, Supplier<String> messageSupplier)
```

```java
@Test
void testCase() {

	boolean trueBool = true;
	boolean falseBool = false;

	Assertions.assertTrue(trueBool);
	Assertions.assertTrue(falseBool, "test execution message");
	Assertions.assertTrue(falseBool, AppTest::message);
	Assertions.assertTrue(AppTest::getResult, AppTest::message);

	Assertions.assertFalse(falseBool);
	Assertions.assertFalse(trueBool, "test execution message");
	Assertions.assertFalse(trueBool, AppTest::message);
	Assertions.assertFalse(AppTest::getResult, AppTest::message);
}

private static String message () {
	return "Test execution result";
}

private static boolean getResult () {
	return true;
}

```

## `Assertions.assertThrows()`示例

它断言所提供的`Executable`的执行将引发`expectedType`的异常并返回该异常。

```java
public static <T extends Throwable> T assertThrows(Class<T> expectedType, 
	Executable executable)
```

```java
@Test
void testCase() {

	Throwable exception = Assertions.assertThrows(IllegalArgumentException.class, () -> {
        throw new IllegalArgumentException("error message");
    });
}

```

## `Assertions.fail()`示例

`fail()`方法仅使测试失败。 它具有以下重载方法：

```java
public static void fail(String message)
public static void fail(Throwable cause)
public static void fail(String message, Throwable cause)
public static void fail(Supplier<String> messageSupplier)
```

```java
public class AppTest {
	@Test
	void testCase() {

		Assertions.fail("not found good reason to pass");
		Assertions.fail(AppTest::message);
	}

	private static String message () {
		return "not found good reason to pass";
	}
}

```

将我的问题放在评论部分。

学习愉快！