0
# Google Truth
1
2
Google Truth is a fluent assertion framework for Java that provides clear, readable test assertions and informative failure messages. Similar to AssertJ, it natively supports many JDK and Guava types, and it is extensible to others. Truth is owned and maintained by the Guava team and is used in the majority of the tests in Google's own codebase.
3
4
## Package Information
5
6
- **Package Name**: com.google.truth:truth
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: Add to Maven `pom.xml`:
10
```xml
11
<dependency>
12
<groupId>com.google.truth</groupId>
13
<artifactId>truth</artifactId>
14
<version>1.4.4</version>
15
<scope>test</scope>
16
</dependency>
17
```
18
19
## Core Imports
20
21
```java
22
import static com.google.common.truth.Truth.assertThat;
23
import static com.google.common.truth.Truth.assertWithMessage;
24
```
25
26
For custom subjects:
27
```java
28
import static com.google.common.truth.Truth.assertAbout;
29
import com.google.common.truth.Subject;
30
```
31
32
## Basic Usage
33
34
```java
35
import static com.google.common.truth.Truth.assertThat;
36
37
// Basic assertions
38
assertThat("actual").isEqualTo("expected");
39
assertThat(42).isGreaterThan(20);
40
assertThat(list).contains("item");
41
42
// With custom failure messages
43
assertWithMessage("User should be active").that(user.isActive()).isTrue();
44
45
// Collection assertions
46
assertThat(Arrays.asList(1, 2, 3))
47
.containsExactly(1, 2, 3)
48
.inOrder();
49
```
50
51
## Architecture
52
53
Truth is built around several key components:
54
55
- **Entry Points**: `Truth` class provides static factory methods for creating assertion chains
56
- **Subject Hierarchy**: 40+ specialized subject classes for different types (String, Integer, Iterable, etc.)
57
- **Builder Pattern**: `StandardSubjectBuilder` allows message customization and custom subject creation
58
- **Extension System**: `Subject.Factory` and `CustomSubjectBuilder` enable custom assertion types
59
- **Failure Strategy**: Pluggable failure handling with rich error messages and facts
60
61
## Capabilities
62
63
### Core Assertions
64
65
Foundation assertion methods available on all subjects for equality, nullity, type checking, and basic comparisons.
66
67
```java { .api }
68
// Truth entry points
69
public static StandardSubjectBuilder assert_();
70
public static StandardSubjectBuilder assertWithMessage(String message);
71
public static StandardSubjectBuilder assertWithMessage(String format, Object... args);
72
73
// Extension entry points
74
public static <S extends Subject, T> SimpleSubjectBuilder<S, T> assertAbout(Subject.Factory<S, T> factory);
75
public static <T extends CustomSubjectBuilder> T assertAbout(CustomSubjectBuilder.Factory<T> factory);
76
77
// Core assertThat methods
78
public static Subject assertThat(Object actual);
79
public static <T extends Comparable<?>> ComparableSubject<T> assertThat(T actual);
80
public static BooleanSubject assertThat(Boolean actual);
81
public static ClassSubject assertThat(Class<?> actual);
82
83
// Basic Subject methods
84
public void isNull();
85
public void isNotNull();
86
public void isEqualTo(Object expected);
87
public void isNotEqualTo(Object expected);
88
public void isSameInstanceAs(Object expected);
89
public void isNotSameInstanceAs(Object expected);
90
public void isInstanceOf(Class<?> type);
91
public void isNotInstanceOf(Class<?> type);
92
```
93
94
[Core Assertions](./core-assertions.md)
95
96
### String Assertions
97
98
Comprehensive string-specific assertion methods for length, content, pattern matching, and case-insensitive comparisons.
99
100
```java { .api }
101
public static StringSubject assertThat(String actual);
102
103
// Key StringSubject methods
104
public void isEmpty();
105
public void isNotEmpty();
106
public void hasLength(int expectedLength);
107
public void contains(CharSequence expectedSubstring);
108
public void startsWith(String prefix);
109
public void endsWith(String suffix);
110
public void matches(String regex);
111
public void containsMatch(String regex);
112
```
113
114
[String Assertions](./string-assertions.md)
115
116
### Numeric Assertions
117
118
Type-safe numeric assertions with comparison operations and tolerance-based floating-point comparisons.
119
120
```java { .api }
121
public static IntegerSubject assertThat(Integer actual);
122
public static LongSubject assertThat(Long actual);
123
public static DoubleSubject assertThat(Double actual);
124
public static FloatSubject assertThat(Float actual);
125
public static BigDecimalSubject assertThat(BigDecimal actual);
126
127
// ComparableSubject methods (inherited by numeric types)
128
public void isAtLeast(T other);
129
public void isAtMost(T other);
130
public void isGreaterThan(T other);
131
public void isLessThan(T other);
132
133
// Tolerance-based comparisons for floating-point types
134
public TolerantDoubleComparison isWithin(double tolerance);
135
public TolerantFloatComparison isWithin(float tolerance);
136
```
137
138
[Numeric Assertions](./numeric-assertions.md)
139
140
### Collection Assertions
141
142
Rich assertion methods for iterables, lists, sets, and other collections including size, containment, ordering, and exact matching.
143
144
```java { .api }
145
public static IterableSubject assertThat(Iterable<?> actual);
146
147
// Core collection methods
148
public void isEmpty();
149
public void isNotEmpty();
150
public void hasSize(int expectedSize);
151
public void contains(Object element);
152
public void containsExactly(Object... elements);
153
public void containsExactlyElementsIn(Iterable<?> expected);
154
public void containsAtLeast(Object... elements);
155
public void containsAnyOf(Object... elements);
156
public void containsNoneOf(Object... elements);
157
158
// Ordering assertions
159
public void isInOrder();
160
public void isInStrictOrder();
161
public Ordered containsExactly(Object... elements);
162
```
163
164
[Collection Assertions](./collection-assertions.md)
165
166
### Map Assertions
167
168
Specialized assertions for maps including key-value pair validation, entry containment, and size verification.
169
170
```java { .api }
171
public static MapSubject assertThat(Map<?, ?> actual);
172
173
// Map-specific methods
174
public void containsKey(Object key);
175
public void doesNotContainKey(Object key);
176
public void containsEntry(Object key, Object value);
177
public void doesNotContainEntry(Object key, Object value);
178
public void containsExactly();
179
public void containsExactly(Object k1, Object v1, Object k2, Object v2, ...);
180
public void containsExactlyEntriesIn(Map<?, ?> expectedMap);
181
```
182
183
[Map Assertions](./map-assertions.md)
184
185
### Guava Collection Assertions
186
187
Specialized assertions for Guava collection types including Multimap, Multiset, Table, and Optional.
188
189
```java { .api }
190
public static MultimapSubject assertThat(Multimap<?, ?> actual);
191
public static MultisetSubject assertThat(Multiset<?> actual);
192
public static TableSubject assertThat(Table<?, ?, ?> actual);
193
public static GuavaOptionalSubject assertThat(com.google.common.base.Optional<?> actual);
194
195
// Guava collection-specific methods available on respective subjects
196
public void containsKey(Object key);
197
public void containsEntry(Object key, Object value);
198
public void hasSize(int expectedSize);
199
```
200
201
### Path Assertions
202
203
File system path assertions for Java NIO Path objects.
204
205
```java { .api }
206
public static PathSubject assertThat(Path actual);
207
```
208
209
### Array Assertions
210
211
Comprehensive array support for both object arrays and all primitive array types with collection-like assertion methods.
212
213
```java { .api }
214
public static <T> ObjectArraySubject<T> assertThat(T[] actual);
215
public static PrimitiveBooleanArraySubject assertThat(boolean[] actual);
216
public static PrimitiveIntArraySubject assertThat(int[] actual);
217
public static PrimitiveLongArraySubject assertThat(long[] actual);
218
public static PrimitiveDoubleArraySubject assertThat(double[] actual);
219
public static PrimitiveFloatArraySubject assertThat(float[] actual);
220
public static PrimitiveByteArraySubject assertThat(byte[] actual);
221
public static PrimitiveCharArraySubject assertThat(char[] actual);
222
public static PrimitiveShortArraySubject assertThat(short[] actual);
223
```
224
225
[Array Assertions](./array-assertions.md)
226
227
### Exception Assertions
228
229
Specialized assertions for throwables and exceptions including message and cause chain validation.
230
231
```java { .api }
232
public static ThrowableSubject assertThat(Throwable actual);
233
234
// ThrowableSubject methods
235
public StringSubject hasMessageThat();
236
public ThrowableSubject hasCauseThat();
237
```
238
239
[Exception Assertions](./exception-assertions.md)
240
241
### Java 8+ Type Assertions
242
243
Modern Java type support for Optional, Stream, and primitive optional types with appropriate assertion methods.
244
245
```java { .api }
246
public static OptionalSubject assertThat(Optional<?> actual);
247
public static OptionalIntSubject assertThat(OptionalInt actual);
248
public static OptionalLongSubject assertThat(OptionalLong actual);
249
public static OptionalDoubleSubject assertThat(OptionalDouble actual);
250
public static StreamSubject assertThat(Stream<?> actual);
251
public static IntStreamSubject assertThat(IntStream actual);
252
public static LongStreamSubject assertThat(LongStream actual);
253
254
// Optional assertion methods
255
public void isPresent();
256
public void isEmpty();
257
public void hasValue(Object expected);
258
```
259
260
[Java 8+ Assertions](./java8-assertions.md)
261
262
### Custom Assertions and Extensions
263
264
Extension mechanisms for creating custom subject types, correspondence-based comparisons, and advanced assertion patterns.
265
266
```java { .api }
267
public static <S extends Subject, T> SimpleSubjectBuilder<S, T> assertAbout(Subject.Factory<S, T> factory);
268
public static <T extends CustomSubjectBuilder> T assertAbout(CustomSubjectBuilder.Factory<T> factory);
269
270
// Key extension interfaces
271
public interface Subject.Factory<SubjectT extends Subject, ActualT> {
272
SubjectT createSubject(FailureMetadata metadata, ActualT actual);
273
}
274
275
// Correspondence for custom comparisons
276
public abstract class Correspondence<A, E> {
277
public abstract boolean compare(A actual, E expected);
278
public static <A, E> Correspondence<A, E> from(BinaryPredicate<A, E> predicate, String description);
279
}
280
```
281
282
[Custom Assertions](./custom-assertions.md)
283
284
### Advanced Testing Utilities
285
286
Specialized utilities for testing assertion failures, soft assertions with batched failure reporting, and integration with testing frameworks.
287
288
```java { .api }
289
// Expect - TestRule for soft assertions
290
public static Expect create();
291
public <T> Subject that(T actual); // Collects failures instead of throwing
292
293
// ExpectFailure - Testing assertion failures
294
public static AssertionError expectFailure(SimpleSubjectBuilderCallback<?> assertionCallback);
295
public static AssertionError expectFailureAbout(Subject.Factory<S, A> factory, SubjectBuilderCallback<S> assertionCallback);
296
```
297
298
[Testing Utilities](./testing-utilities.md)
299
300
## Types
301
302
```java { .api }
303
// Core builder and subject types
304
public class StandardSubjectBuilder {
305
public StandardSubjectBuilder withMessage(String message);
306
public StandardSubjectBuilder withMessage(String format, Object... args);
307
public <S extends Subject, A> SimpleSubjectBuilder<S, A> about(Subject.Factory<S, A> factory);
308
}
309
310
public class Subject {
311
protected Subject(FailureMetadata metadata, Object actual);
312
public interface Factory<SubjectT extends Subject, ActualT> {
313
SubjectT createSubject(FailureMetadata metadata, ActualT actual);
314
}
315
}
316
317
// Correspondence for custom comparisons
318
public abstract class Correspondence<A, E> {
319
public abstract boolean compare(A actual, E expected);
320
public String formatDiff(A actual, E expected);
321
}
322
323
// Fact for structured failure information
324
public final class Fact {
325
public static Fact fact(String key, Object value);
326
public static Fact simpleFact(String key);
327
}
328
329
// Ordered interface for ordering constraints
330
public interface Ordered {
331
void inOrder();
332
}
333
334
// Failure handling
335
@FunctionalInterface
336
public interface FailureStrategy {
337
void fail(AssertionError failure);
338
}
339
```