“This is my third day of the first Gwen Challenge 2022.First challenge in 2022”
One, foreword
When designing automatic interface Cases, the core principle is 3A (Arrange-> Actor ->Assert);
The power of assertion tools directly affects the efficiency of use cases. This article will introduce a mainstream streaming assertion artifact: AssertJ.
AssertJ Brief introduction
An assertion statement can only assert one checkpoint on an actual value. A streaming assertion statement supports multiple checkpoints on an actual value. AssertJ is a Java library that provides assertions for JDK standard types and can be used with JUnit, TestNG, or any other testing framework. Different major versions of AssertJ depend on different Java versions:
- AssertJ 3.x requires Java 8 or higher
- AssertJ 2.x requires Java 7 or higher
- AssertJ 1.x requires Java 6 or higher
Note that AssertJ 3.x includes all AssertJ 2.x functionality and adds Java 8-specific functionality (such as exception assertions for lambdas)
AssertJ supports the following modules:
-
Core: AssertJ Core is a Java library that provides a Fluent interface for writing assertions.
-
Assertions Generator: Use the Assertion generator to create Assertions specific to your own classes.
-
Guava: AssertJ assertions for Guava provides assertions for Guava types like Multimap, Table, Optional, Range or ByteSource.
-
Joda-time: AssertJ assertions for joda-time provides assertions for joda-time types like DateTime and LocalDateTime.
-
DB: AssertJ-DB provides assertions to test data in a database.
-
Neo4j: Provides assertions for Neo4j 3 or higher.
-
Swing: AssertJ Swing is a Java library that provides a Fluent interface for functional Swing UI testing.
A detailed list of all modules is available on the official website. Address: Joel – costigliola. Making. IO/assertj/ind…
Let’s start with a few examples, directly from the official AssertJ documentation:
assertThat(frodo)
.isNotEqualTo(sauron)
.isIn(fellowshipOfTheRing);
assertThat(frodo.getName())
.startsWith("Fro")
.endsWith("do")
.isEqualToIgnoringCase("frodo");
assertThat(fellowshipOfTheRing)
.hasSize(9)
.contains(frodo, sam)
.doesNotContain(sauron);
Copy the code
The examples above are just the tip of the iceberg
Three, AssertJ use
1, guide package
AssertJ is built into SpringBoot. You only need to import the spring-boot-starter-test dependency package
<dependencies>
<! -- Introduce efficiency plugin -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<! -- Test package -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<! Testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
</dependency>
</dependencies>
Copy the code
2. For entry
To write an assertion, you always need to pass the object to the assert.assertthat () method before acting on the actual assertion.
It is important to remember that, unlike some other libraries, the following code does not actually assert anything and will never fail a test:
assertThat(anyRefenceOrValue);
Copy the code
If you use the IDE’s code completion feature, writing AssertJ assertions is surprisingly easy because of its very descriptive approach. Here it isIntelliJ IDEA
The appearance of:As you can see, there are a number of contextual methods to choose from, and these only apply to strings.
Object assertions
Objects can be compared in various ways to determine the equality of two objects or to examine the fields of objects.
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Dog {
private String name;
private Float weight;
}
Copy the code
Let’s look at two ways in which we can compare the equality of two objects. Consider the following two Dog objects, Fido and fidosClone
@test (description = "object assertion 1")
public void whenComparingReferences_thenNotEqual(a) {
// Instantiate two objects
Dog fidos= new Dog("fidos".5.14 f);
Dog fidosClone = new Dog("fidosClone".5.14 f);
Asserts two object references
assertThat(fidos).isNotEqualTo(fidosClone);
}
Copy the code
IsEqualTo () is a comparison object reference, so it will fail. If we want to compare their content, we can use isEqualToComparingFieldByFieldRecursively ()
@test (description = "object assertion 2")
public void whenComparingFields_thenEqual(a) {
// Instantiate two objects
Dog fido = new Dog("Fido".5.15 f);
Dog fidosClone = new Dog("Fido".5.15 f);
// Assert two object contents
assertThat(fido).isEqualToComparingFieldByFieldRecursively(fidosClone);
}
Copy the code
When performing recursive fields through field comparisons, Fido and fidosClone are equal because each field in one object is compared to a field in the other object.
There are many other assertion methods that provide different ways to compare and shrink objects and to examine and assert their fields. See the official AbstractObjectAssert API for details.
4. Bull asserted
There are some simple ways to test for truth:
- isTrue()
- isFalse()
Here’s an example:
@test (description = "Boolean assertion ")
public void whenisEmpty_isTrue(a) {
// instantiate the object
Dog fido = new Dog("Fido".5.15 f);
// Assert whether the field is empty
assertThat(fido.getName().isEmpty()).isTrue();
}
Copy the code
Iterable/Array predicate
For Iterable or Array, there are several ways to assert the existence of their contents. One of the most common assertions is to check whether Iterable or Array contains a given element:
Or if List is not empty:
assertThat(list).isNotEmpty();
Copy the code
Or if List begins with a given character. For example “1” :
assertThat(list).startsWith("1");
Copy the code
If you want to create multiple assertions for the same object, you can easily wire them together. Here is an example of an assertion that checks if the supplied list is empty, contains the element “1”, does not contain any null values, and contains the element sequence “2”, “3” :
assertThat(list)
.isNotEmpty()
.contains("1")
.doesNotContainNull()
.containsSequence("2"."3");
Copy the code
Of course, there are more possible assertions for those types. See the official AbstractIterableAssert API for details
Complete example:
@test (description = "Iterable/Array predicate 1")
public void whenCheckingForElement_thenContains(a){
List<String> list = Arrays.asList("1"."2"."3");
// Assert whether the given element is contained
assertThat(list).contains("1");
}
@test (description = "Iterable/Array predicate 2")
public void whenCheckingForElement_thenMultipleAssertions(a) {
List<String> list = Arrays.asList("1"."2"."3");
// Assert that the list is not empty
assertThat(list).isNotEmpty();
// Assert that list begins with the given field
assertThat(list).startsWith("1");
// Assert that list does not contain NULL
assertThat(list).doesNotContainNull();
// Multiple assertions
assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2"."3");
}
Copy the code
Character assertion
Assertions of character types mainly involve comparing and even checking whether a given character is from a Unicode table. Here is an example of an assertion that checks whether the supplied character is not ‘a’ and, in Unicode tables, greater than ‘b’ and lowercase:
assertThat(someCharacter)
.isNotEqualTo('a')
.inUnicode()
.isGreaterThanOrEqualTo('b')
.isLowerCase();
Copy the code
For a detailed list of all character type assertions, see the AbstractCharacterAssert API complete example:
@test (description = "character assertion ")
public void whenCheckingCharacter_thenIsUnicode(a) {
char someCharacter = 'c';
// Asserts whether the character is not 'a' and, in Unicode tables, is greater than 'b' and lowercase
assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase();
}
Copy the code
Class assertions
Assertions of Class types mainly check for fields, Class types, the existence of annotations, and finality of the Class.
If you want to assert that the Runnable class is an interface, you simply write:
assertThat(Runnable.class).isInterface();
Copy the code
Or if you want to check if a class can be assigned from another class:
assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class);
Copy the code
You can view all possible class assertions in the AbstractClassAssert API. Complete example:
@test (description = "class assertion 1")
public void whenCheckingRunnable_thenIsInterface(a) {
// Assert that the Runnable class is an interface
assertThat(Runnable.class).isInterface();
}
@test (description = "class assertion 2")
public void whenAssigningNSEExToException_thenIsAssignable(a){
// Assert whether a class can be allocated from another class
assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class);
}
Copy the code
8. File assertions
File assertions are all about checking whether a given file instance exists, is a directory or a file, has something in it, is readable or has an extension.
Here is an example of an assertion that checks if a given file exists, is a file and not a directory, and is read-write:
assertThat(someFile)
.exists()
.isFile()
.canRead()
.canWrite();
Copy the code
You can view all possible class assertions in the AbstractFileAssert API.
Complete example:
@test (description = "file assertion ")
public void whenCheckingFile_then(a) throws IOException {
final File someFile = File.createTempFile("aaa"."bbb");
someFile.deleteOnExit();
// Assert whether a file exists, is a file, not a directory, and can be read and written
assertThat(someFile).exists().isFile().canRead().canWrite();
}
Copy the code
Double/Float/Integer assertion
Numeric assertions are all about comparing values with or without a given offset. For example, if we want to check whether two values are equal based on a given precision, we can do the following:
assertThat(5.1).isEqualTo(5, withPrecision(1d));
Copy the code
Note that we use the imported withPrecision helper method to generate the offset object.
For more assertions, visit the AbstractDoubleAssert API.
InputStream assertion
There is only one inputStream-specific assertion available:
hasSameContentAs
(Expected InputStream)
Usage:
assertThat(given).hasSameContentAs(expected);
Copy the code
Complete example:
@test (description = "InputStream assertion ")
public void whenCheckingIS_then(a) {
InputStream given = new ByteArrayInputStream("foo".getBytes());
InputStream expected = new ByteArrayInputStream("foo".getBytes());
// Assert whether to expect an InputStream
assertThat(given).hasSameContentAs(expected);
}
Copy the code
11. Map assertion
Map assertions allow you to check whether a Map contains certain items, item sets, or keys/values separately. You can see an example of an assertion that checks if a given Map is empty, contains key “2”, does not contain the number key “10” and contains entries: key:2,value: “a” :
assertThat(map)
.isNotEmpty()
.containsKey(2)
.doesNotContainKeys(10)
.contains(entry(2."a"));
Copy the code
For more assertions, see the AbstractMapAssert API.
Complete example:
@test (description = "Map assertion ")
public void whenGivenMap_then(a) {
Map<Integer, String> map = Maps.newHashMap(2."a");
// Assert whether the Map is empty, containing key "2", not key "10", and containing elements: key:2,value: "a"
assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2."a"));
}
Copy the code
12, Throwable assertion
Throwable assertions allow, for example, checking for exception information, traces, cause checks, or exceptions thrown for validation.
Let’s look at an example of an assertion that checks if a given exception was thrown and the message ends in “C” :
assertThat(ex).hasNoCause().hasMessageEndingWith("c");
Copy the code
For more assertions, see the AbstractThrowableAssert API. Complete example:
@test (description = "Throwable assertion ")
public void whenGivenException_then(a) {
Exception ex = new Exception("abc");
Asserts whether the given exception was thrown and the message ends with "c"
assertThat(ex).hasNoCause().hasMessageEndingWith("c");
}
Copy the code
13. Describe assertions
For a higher level of detail, you can create dynamically generated custom descriptions for assertions. The key to doing this is as (String description, Object… Args) method.
If you define an assertion like this:
assertThat(fidos.getWeight())
.as("%s's age should be equal to 5.15f")
.isEqualTo(5.15 f);
Copy the code
Here’s what happens when you run the test:
org.junit.ComparisonFailure: [%sAge should be equal to 5.15 F] Expected :5.1[5] F Actual :5.1[4] FCopy the code
Complete example:
@test (description = "description assertion ")
public void whenRunningAssertion_thenDescribed(a) throws Exception {
Dog fidos= new Dog("fidos".5.14 f);
assertThat(fidos.getWeight()).as("%s's age should be equal to 5.15f").isEqualTo(5.15 f);
}
Copy the code
Four, summary
In this article, we briefly explored the use of AssertJ to provide the most popular streaming assertions for core Java types.
Source code:
- Github.com/zuozewei/bl…