-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHamcrestTest.java
More file actions
58 lines (46 loc) · 2.13 KB
/
HamcrestTest.java
File metadata and controls
58 lines (46 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.github.timtebeek.betterassertions.hamcrest;
import com.github.timtebeek.betterassertions.Book;
import com.github.timtebeek.betterassertions.Bundle;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
class HamcrestTest {
// Hamcrest
// - Requires various static imports; harder to discover the available matchers
// + Allows for writing custom matchers, as the Spring team has done
@Test
void bundle() {
List<Book> books = new Bundle().getBooks();
assertThat(books, is(not(nullValue())));
assertThat(books, hasSize(3));
assertThat(books, hasItem(new Book("Effective Java", "Joshua Bloch", 2001)));
assertThat(books, hasItem(new Book("Java Concurrency in Practice", "Brian Goetz", 2006)));
assertThat(books, hasItem(new Book("Clean Code", "Robert C. Martin", 2008)));
assertThat(books, not(hasItem(new Book("Java 8 in Action", "Raoul-Gabriel Urma", 2014))));
}
// Incorrect usage of Hamcrest
// - `hasItem` and `contains` are not interchangeable
@Disabled
@Test
void failingTest() {
List<Book> books = new Bundle().getBooks();
// Wrong way with Hamcrest:
assertThat(books, contains(new Book("Effective Java", "Joshua Bloch", 2001)));
assertThat(books, contains(new Book("Java Concurrency in Practice", "Brian Goetz", 2006)));
assertThat(books, contains(new Book("Clean Code", "Robert C. Martin", 2008)));
// Correct way with Hamcrest:
assertThat(books, contains(
new Book("Effective Java", "Joshua Bloch", 2001),
new Book("Java Concurrency in Practice", "Brian Goetz", 2006),
new Book("Clean Code", "Robert C. Martin", 2008)
));
// Not always clear what's correct
}
}