Table of Contents
ToggleIntroduction to AssertJ - AssertJ 155
介紹 AssertJ 一個開源的程式庫,用於在 Java 測試中編寫流暢且豐富的斷言,透過 AssertJ Introduction 流式斷言,可以大幅提升斷言效率,讓開發者體驗更流暢的驗證斷言,本篇增加了範例,透過單元測試來驗證產出結果。
檔案目錄
./
+- src
+- test
| +- org
| +- ruoxue
| +- spring_boot_168
| +- test
| +- assertj
| +- IntroductionAssertJTest.java
Dependencies
提供了一系列類別和實用方法,支援如下:
Standard Java
Java 8
Guava
Joda Time
Neo4J and
Swing components
介紹使用基本模組 AssertJ-core ,從 AssertJ 3.5.1 版本開始,就已經支援 Java 8 ,因此須將引用其程式庫,若使用 Java 7 或是更早之前的版本,則須引用 AssertJ 2.x.x。
Maven
pom.xml
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.23.1</version>
<scope>test</scope>
</dependency>
Gradle
build.gradle
dependencies {
testImplementation "org.assertj:assertj-core:3.23.1"
}
單元測試
Fluent Assertions Java Library 斷言物件的主要目的是取得物件以進行斷言。
Fruit
建立 Fruit 類別,覆寫 toString ,定義屬性和方法,用來建立一個物件。
@NoArgsConstructor
@Getter
@Setter
public static class Fruit {
private String name;
private double quantity;
private int type;
private List<String> origins = new ArrayList<>();
public Fruit(String name, double quantity, int type) {
this.name = name;
this.quantity = quantity;
this.type = type;
}
public String toString() {
ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.JSON_STYLE);
builder.appendSuper(super.toString());
builder.append("name", name);
builder.append("quantity", quantity);
builder.append("type", type);
builder.append("origins", origins);
return builder.toString();
}
}
Boolean Assertions
驗證是否真假,若不成立,則會拋出 AssertionError 。
@Test
public void booleanAssertions() {
String value = "AssertJ";
System.out.println(value);
assertThat(value.startsWith("A")).isTrue();
String value2 = "";
System.out.println(value2);
assertThat(value2.isEmpty()).isTrue();
}
AssertJ
Character Assertions
Fluent Assertions Java Library 驗證字元是否符合條件,若不成立,則會拋出 AssertionError 。
@Test
public void characterAssertions() {
char value = 'A';
System.out.println(value);
assertThat(value).isNotEqualTo('a').inUnicode().isLessThanOrEqualTo('b').isUpperCase();
char value2 = '1';
System.out.println(value2);
assertThat(value2).isEqualTo('1').isIn('1', '5').isGreaterThan('/');
}
A
1
String Assertions
Fluent Assertions Java Library 驗證字串是否符合條件,若不成立,則會拋出 AssertionError 。
@Test
public void stringAssertions() {
String value = "AssertJ 155";
System.out.println(value);
Condition<String> length = new Condition<String>(s -> s.length() > 10, "length");
assertThat(value).matches(s -> s.length() < 12).is(length);
String value2 = "AssertJ";
System.out.println(value2);
Condition<String> length2 = new Condition<String>(s -> s.length() > 6, "length");
assertThat(value2).matches(s -> s.length() < 8).is(length2);
}
AssertJ 155
AssertJ
Number Assertions
Fluent Assertions Java Library 驗證數字是否符合條件,若不成立,則會拋出 AssertionError 。
@Test
public void numberAssertions() {
int value = 155;
System.out.println(value);
assertThat(value).isPositive().isGreaterThan(150).isCloseTo(150, within(5));
double doubleValue = 151.2d;
System.out.println(doubleValue);
assertThat(doubleValue).isNotZero().isLessThan(152d);
}
155
151.2
Array Assertions
Improve Unit Tests with AssertJ 驗證陣列是否符合條件,若不成立,則會拋出 AssertionError 。
@Test
public void arrayAssertions() {
Fruit durian = new Fruit("Durian", Double.MAX_VALUE, 2);
Fruit guava = new Fruit("Guava", 1, 2);
Fruit pitaya = new Fruit("Pitaya", -1, 2);
Fruit[] array = new Fruit[] { durian, guava, pitaya };
System.out.println(Arrays.deepToString(array));
assertThat(array).allMatch(e -> e.getName().length() > 4).contains(durian, guava, pitaya);
assertThat(array).allMatch(e -> e.getType() == 2).hasSize(3);
int[] intArray = new int[] { 1, 2, 3, 4, 5 };
System.out.println(Arrays.toString(intArray));
assertThat(intArray).isNotNull().containsAnyOf(1, 9).containsSequence(3, 4);
}
[{"name":"Durian","quantity":1.7976931348623157E308,"type":2,"origins":[]}, {"name":"Guava","quantity":1.0,"type":2,"origins":[]}, {"name":"Pitaya","quantity":-1.0,"type":2,"origins":[]}]
[1, 2, 3, 4, 5]
List Assertions
Improve Unit Tests with AssertJ 驗證集合是否符合條件,若不成立,則會拋出 AssertionError 。
@Test
public void listAssertions() {
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
System.out.println(list);
assertThat(list).isNotNull().doesNotContainNull().contains("Banana", "Apple").containsSequence("Banana",
"Cherry");
List<Integer> intList = Stream.of(6, 7, 8, 9, 10).collect(Collectors.toList());
System.out.println(intList);
Condition<Integer> intValue = new Condition<Integer>(i -> i > 0, "value");
assertThat(intList).isNotEmpty().are(intValue);
}
[Apple, Banana, Cherry]
[6, 7, 8, 9, 10]
Map Assertions
Improve Unit Tests with AssertJ 驗證映射是否符合條件,若不成立,則會拋出 AssertionError 。
@Test
public void mapAssertions() {
Map<String, Integer> map = new HashMap<>();
map.put("Grape", 18);
map.put("Kiwifruit", 19);
map.put("Lemon", 20);
System.out.println(map);
assertThat(map).isNotNull().containsKey("Kiwifruit").containsAnyOf(entry("Lemon", 20));
Map<Integer, Integer> intMap = new HashMap<>();
intMap.put(1, 18);
intMap.put(2, 19);
intMap.put(3, 20);
System.out.println(intMap);
assertThat(intMap).isNotEmpty().containsEntry(1, 18);
}
{Grape=18, Kiwifruit=19, Lemon=20}
{1=18, 2=19, 3=20}
IntroductionAssertJTest.java
Improve Unit Tests with AssertJ 新增單元測試,驗證是否符合預期。
package org.ruoxue.spring_boot_168.test.assertj;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.Test;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
public class IntroductionAssertJTest {
@NoArgsConstructor
@Getter
@Setter
@Builder
public static class Fruit {
private String name;
private double quantity;
private int type;
private List<String> origins = new ArrayList<>();
public Fruit(String name, double quantity, int type, List<String> origins) {
this.name = name;
this.quantity = quantity;
this.type = type;
this.origins = origins;
}
public Fruit(String name, double quantity, int type) {
this(name, quantity, type, new ArrayList<>());
}
public String toString() {
ToStringBuilder builder = new ToStringBuilder(this, ToStringStyle.JSON_STYLE);
builder.appendSuper(super.toString());
builder.append("name", name);
builder.append("quantity", quantity);
builder.append("type", type);
builder.append("origins", origins);
return builder.toString();
}
}
@Test
public void booleanAssertions() {
String value = "AssertJ";
System.out.println(value);
assertThat(value.startsWith("A")).isTrue();
String value2 = "";
System.out.println(value2);
assertThat(value2.isEmpty()).isTrue();
}
@Test
public void characterAssertions() {
char value = 'A';
System.out.println(value);
assertThat(value).isNotEqualTo('a').inUnicode().isLessThanOrEqualTo('b').isUpperCase();
char value2 = '1';
System.out.println(value2);
assertThat(value2).isEqualTo('1').isIn('1', '5').isGreaterThan('/');
}
@Test
public void stringAssertions() {
String value = "AssertJ 155";
System.out.println(value);
Condition<String> length = new Condition<String>(s -> s.length() > 10, "length");
assertThat(value).matches(s -> s.length() < 12).is(length);
String value2 = "AssertJ";
System.out.println(value2);
Condition<String> length2 = new Condition<String>(s -> s.length() > 6, "length");
assertThat(value2).matches(s -> s.length() < 8).is(length2);
}
@Test
public void numberAssertions() {
int value = 155;
System.out.println(value);
assertThat(value).isPositive().isGreaterThan(150).isCloseTo(150, within(5));
double doubleValue = 151.2d;
System.out.println(doubleValue);
assertThat(doubleValue).isNotZero().isLessThan(152d);
}
@Test
public void arrayAssertions() {
Fruit durian = new Fruit("Durian", Double.MAX_VALUE, 2);
Fruit guava = new Fruit("Guava", 1, 2);
Fruit pitaya = new Fruit("Pitaya", -1, 2);
Fruit[] array = new Fruit[] { durian, guava, pitaya };
System.out.println(Arrays.deepToString(array));
assertThat(array).allMatch(e -> e.getName().length() > 4).contains(durian, guava, pitaya);
assertThat(array).allMatch(e -> e.getType() == 2).hasSize(3);
int[] intArray = new int[] { 1, 2, 3, 4, 5 };
System.out.println(Arrays.toString(intArray));
assertThat(intArray).isNotNull().containsAnyOf(1, 9).containsSequence(3, 4);
}
@Test
public void listAssertions() {
List<String> list = Arrays.asList("Apple", "Banana", "Cherry");
System.out.println(list);
assertThat(list).isNotNull().doesNotContainNull().contains("Banana", "Apple").containsSequence("Banana",
"Cherry");
List<Integer> intList = Stream.of(6, 7, 8, 9, 10).collect(Collectors.toList());
System.out.println(intList);
Condition<Integer> intValue = new Condition<Integer>(i -> i > 0, "value");
assertThat(intList).isNotEmpty().are(intValue);
}
@Test
public void mapAssertions() {
Map<String, Integer> map = new HashMap<>();
map.put("Grape", 18);
map.put("Kiwifruit", 19);
map.put("Lemon", 20);
System.out.println(map);
assertThat(map).isNotNull().containsKey("Kiwifruit").containsAnyOf(entry("Lemon", 20));
Map<Integer, Integer> intMap = new HashMap<>();
intMap.put(1, 18);
intMap.put(2, 19);
intMap.put(3, 20);
System.out.println(intMap);
assertThat(intMap).isNotEmpty().containsEntry(1, 18);
}
}
心得分享
AssertJ Fluent Assertions for Java 支援字元、字串、數字、 Array 、 List 、 Map 等物件進行斷言,驗證是否符合條件,提供豐富的流式斷言,對於許多測試驗證的場景,可以讓開發者使用更流暢的單元測試,善用 Improve Unit Tests with AssertJ 將大幅提升驗證效率,節省不少撰寫單元測試的時間。
原碼下載