Fluent assertion framework for Java that provides clear, readable test assertions and informative failure messages
—
Modern Java type support for Optional, Stream, and primitive optional types with appropriate assertion methods.
Assertions for Java 8+ Optional types providing comprehensive validation of optional values.
/**
* Creates an OptionalSubject for asserting about Optional values.
* @param actual the Optional under test
*/
public static OptionalSubject assertThat(Optional<?> actual);Methods for basic Optional state validation.
/**
* Fails if the Optional is not present (i.e., isEmpty() returns true).
*/
public void isPresent();
/**
* Fails if the Optional is present (i.e., isPresent() returns true).
*/
public void isEmpty();
/**
* Fails if the Optional does not have the given value.
* @param expected the expected value that should be present
*/
public void hasValue(Object expected);Usage Examples:
// Basic Optional validation
Optional<String> presentValue = Optional.of("hello");
assertThat(presentValue).isPresent();
assertThat(presentValue).hasValue("hello");
Optional<String> emptyValue = Optional.empty();
assertThat(emptyValue).isEmpty();
// Testing Optional in service methods
Optional<User> userResult = userService.findById(123L);
assertThat(userResult).isPresent();
assertThat(userResult).hasValue(expectedUser);Real-world patterns for testing Optional usage in applications.
// Testing Optional chaining
@Test
public void testOptionalChaining() {
Optional<String> result = userService.findById(123L)
.map(User::getEmail)
.filter(email -> email.contains("@"))
.map(String::toLowerCase);
assertThat(result).isPresent();
assertThat(result).hasValue("user@example.com");
}
// Testing Optional with business logic
@Test
public void testOptionalBusinessLogic() {
// When user exists
Optional<User> existingUser = userService.findByEmail("existing@example.com");
assertThat(existingUser).isPresent();
// When user doesn't exist
Optional<User> nonExistentUser = userService.findByEmail("missing@example.com");
assertThat(nonExistentUser).isEmpty();
}
// Testing Optional transformation
@Test
public void testOptionalTransformation() {
Optional<String> input = Optional.of(" HELLO WORLD ");
Optional<String> result = input
.map(String::trim)
.map(String::toLowerCase)
.filter(s -> s.length() > 5);
assertThat(result).isPresent();
assertThat(result).hasValue("hello world");
}Specialized assertions for primitive Optional types with appropriate type-safe methods.
/**
* Creates an OptionalIntSubject for asserting about OptionalInt values.
* @param actual the OptionalInt under test
*/
public static OptionalIntSubject assertThat(OptionalInt actual);
/**
* Fails if the OptionalInt is not present.
*/
public void isPresent();
/**
* Fails if the OptionalInt is present.
*/
public void isEmpty();
/**
* Fails if the OptionalInt does not have the given value.
* @param expected the expected int value that should be present
*/
public void hasValue(int expected);Usage Examples:
// Basic OptionalInt usage
OptionalInt presentInt = OptionalInt.of(42);
assertThat(presentInt).isPresent();
assertThat(presentInt).hasValue(42);
OptionalInt emptyInt = OptionalInt.empty();
assertThat(emptyInt).isEmpty();
// Testing OptionalInt from streams
int[] numbers = {1, 2, 3, 4, 5};
OptionalInt max = Arrays.stream(numbers).max();
assertThat(max).isPresent();
assertThat(max).hasValue(5);
OptionalInt firstEven = Arrays.stream(numbers)
.filter(n -> n % 2 == 0)
.findFirst();
assertThat(firstEven).isPresent();
assertThat(firstEven).hasValue(2);/**
* Creates an OptionalLongSubject for asserting about OptionalLong values.
* @param actual the OptionalLong under test
*/
public static OptionalLongSubject assertThat(OptionalLong actual);
/**
* Fails if the OptionalLong is not present.
*/
public void isPresent();
/**
* Fails if the OptionalLong is present.
*/
public void isEmpty();
/**
* Fails if the OptionalLong does not have the given value.
* @param expected the expected long value that should be present
*/
public void hasValue(long expected);Usage Examples:
// Testing OptionalLong with timestamps
List<Long> timestamps = Arrays.asList(1000000L, 2000000L, 3000000L);
OptionalLong maxTimestamp = timestamps.stream().mapToLong(Long::longValue).max();
assertThat(maxTimestamp).isPresent();
assertThat(maxTimestamp).hasValue(3000000L);
// Testing empty OptionalLong
OptionalLong emptyResult = LongStream.empty().findAny();
assertThat(emptyResult).isEmpty();/**
* Creates an OptionalDoubleSubject for asserting about OptionalDouble values.
* @param actual the OptionalDouble under test
*/
public static OptionalDoubleSubject assertThat(OptionalDouble actual);
/**
* Fails if the OptionalDouble is not present.
*/
public void isPresent();
/**
* Fails if the OptionalDouble is present.
*/
public void isEmpty();
/**
* Fails if the OptionalDouble does not have the given value.
* @param expected the expected double value that should be present
*/
public void hasValue(double expected);Usage Examples:
// Testing OptionalDouble with calculations
double[] measurements = {1.1, 2.2, 3.3, 4.4};
OptionalDouble average = Arrays.stream(measurements).average();
assertThat(average).isPresent();
// Note: For floating-point comparisons, consider using tolerance
// assertThat(average.getAsDouble()).isWithin(0.001).of(2.75);
// Testing empty OptionalDouble
OptionalDouble emptyAverage = DoubleStream.empty().average();
assertThat(emptyAverage).isEmpty();Comprehensive assertions for Java 8+ Stream types with collection-like functionality.
/**
* Creates a StreamSubject for asserting about Stream values.
* @param actual the Stream under test
*/
public static StreamSubject assertThat(Stream<?> actual);Methods for basic Stream validation including size, emptiness, and content.
/**
* Fails if the stream is not empty.
*/
public void isEmpty();
/**
* Fails if the stream is empty.
*/
public void isNotEmpty();
/**
* Fails if the stream does not have the given size.
* @param expectedSize the expected number of elements
*/
public void hasSize(int expectedSize);
/**
* Fails if the stream does not contain exactly the given elements, in any order.
* @param elements the expected elements
*/
public Ordered containsExactly(Object... elements);
/**
* Fails if the stream does not contain exactly the elements in the given iterable, in any order.
* @param expected the iterable containing expected elements
*/
public Ordered containsExactlyElementsIn(Iterable<?> expected);Usage Examples:
// Basic stream validation
Stream<String> fruits = Stream.of("apple", "banana", "cherry");
assertThat(fruits).hasSize(3);
assertThat(fruits).containsExactly("apple", "banana", "cherry");
// Testing empty streams
Stream<Integer> emptyStream = Stream.empty();
assertThat(emptyStream).isEmpty();
// Testing filtered streams
Stream<Integer> evenNumbers = Stream.of(1, 2, 3, 4, 5, 6)
.filter(n -> n % 2 == 0);
assertThat(evenNumbers).containsExactly(2, 4, 6);Real-world patterns for testing Stream operations and transformations.
// Testing stream transformations
@Test
public void testStreamTransformation() {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Stream<String> upperCaseNames = names.stream()
.map(String::toUpperCase)
.filter(name -> name.length() > 3);
assertThat(upperCaseNames).containsExactly("ALICE", "CHARLIE");
}
// Testing stream reductions
@Test
public void testStreamReduction() {
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5);
// Note: Stream can only be consumed once, so create fresh streams for each test
int sum = Stream.of(1, 2, 3, 4, 5).mapToInt(Integer::intValue).sum();
assertThat(sum).isEqualTo(15);
Optional<Integer> max = Stream.of(1, 2, 3, 4, 5).max(Integer::compareTo);
assertThat(max).isPresent();
assertThat(max).hasValue(5);
}
// Testing stream grouping and collecting
@Test
public void testStreamGrouping() {
List<String> words = Arrays.asList("apple", "banana", "apricot", "blueberry");
Map<Character, List<String>> groupedByFirstLetter = words.stream()
.collect(Collectors.groupingBy(word -> word.charAt(0)));
assertThat(groupedByFirstLetter).containsKey('a');
assertThat(groupedByFirstLetter).containsKey('b');
assertThat(groupedByFirstLetter.get('a')).containsExactly("apple", "apricot");
assertThat(groupedByFirstLetter.get('b')).containsExactly("banana", "blueberry");
}Specialized assertions for primitive stream types.
/**
* Creates an IntStreamSubject for asserting about IntStream values.
* @param actual the IntStream under test
*/
public static IntStreamSubject assertThat(IntStream actual);Usage Examples:
// Testing IntStream operations
IntStream numbers = IntStream.range(1, 6); // 1, 2, 3, 4, 5
assertThat(numbers).hasSize(5);
assertThat(numbers).containsExactly(1, 2, 3, 4, 5).inOrder();
// Testing IntStream transformations
IntStream evenSquares = IntStream.range(1, 11)
.filter(n -> n % 2 == 0)
.map(n -> n * n);
assertThat(evenSquares).containsExactly(4, 16, 36, 64, 100);
// Testing IntStream statistics
IntStream.Builder builder = IntStream.builder();
IntStream data = builder.add(10).add(20).add(30).build();
assertThat(data).hasSize(3);/**
* Creates a LongStreamSubject for asserting about LongStream values.
* @param actual the LongStream under test
*/
public static LongStreamSubject assertThat(LongStream actual);Usage Examples:
// Testing LongStream with large numbers
LongStream largeNumbers = LongStream.of(1000000L, 2000000L, 3000000L);
assertThat(largeNumbers).hasSize(3);
assertThat(largeNumbers).containsExactly(1000000L, 2000000L, 3000000L).inOrder();
// Testing LongStream range operations
LongStream range = LongStream.rangeClosed(100L, 105L);
assertThat(range).containsExactly(100L, 101L, 102L, 103L, 104L, 105L).inOrder();// Remember: Streams can only be consumed once
@Test
public void testStreamConsumption() {
Supplier<Stream<String>> streamSupplier = () ->
Stream.of("apple", "banana", "cherry");
// Test size
assertThat(streamSupplier.get()).hasSize(3);
// Test contents (need fresh stream)
assertThat(streamSupplier.get()).containsExactly("apple", "banana", "cherry");
// Test filtered contents (need fresh stream)
assertThat(streamSupplier.get().filter(s -> s.contains("a")))
.containsExactly("apple", "banana");
}// Testing parallel stream operations
@Test
public void testParallelStreamProcessing() {
List<Integer> numbers = IntStream.range(1, 1001)
.boxed()
.collect(Collectors.toList());
Stream<Integer> parallelSquares = numbers.parallelStream()
.map(n -> n * n)
.filter(n -> n > 100);
// Note: Parallel streams may not preserve order
assertThat(parallelSquares).isNotEmpty();
// For ordered assertions with parallel streams, use collect first
List<Integer> result = numbers.parallelStream()
.map(n -> n * n)
.filter(n -> n <= 25)
.sorted()
.collect(Collectors.toList());
assertThat(result).containsExactly(1, 4, 9, 16, 25).inOrder();
}// Testing Stream operations that produce Optional
@Test
public void testStreamOptionalIntegration() {
List<String> words = Arrays.asList("cat", "elephant", "dog", "hippopotamus");
Optional<String> longestWord = words.stream()
.max(Comparator.comparing(String::length));
assertThat(longestWord).isPresent();
assertThat(longestWord).hasValue("hippopotamus");
Optional<String> shortestWordStartingWithZ = words.stream()
.filter(word -> word.startsWith("z"))
.min(Comparator.comparing(String::length));
assertThat(shortestWordStartingWithZ).isEmpty();
}/**
* Subject class for making assertions about Optional values.
*/
public class OptionalSubject extends Subject {
/**
* Constructor for OptionalSubject.
* @param metadata failure metadata for context
* @param actual the Optional under test
*/
protected OptionalSubject(FailureMetadata metadata, Optional<?> actual);
/**
* Fails if the Optional is not present.
*/
public void isPresent();
/**
* Fails if the Optional is present.
*/
public void isEmpty();
/**
* Fails if the Optional does not have the given value.
* @param expected the expected value
*/
public void hasValue(Object expected);
}
/**
* Subject class for making assertions about OptionalInt values.
*/
public class OptionalIntSubject extends Subject {
protected OptionalIntSubject(FailureMetadata metadata, OptionalInt actual);
public void isPresent();
public void isEmpty();
public void hasValue(int expected);
}
/**
* Subject class for making assertions about OptionalLong values.
*/
public class OptionalLongSubject extends Subject {
protected OptionalLongSubject(FailureMetadata metadata, OptionalLong actual);
public void isPresent();
public void isEmpty();
public void hasValue(long expected);
}
/**
* Subject class for making assertions about OptionalDouble values.
*/
public class OptionalDoubleSubject extends Subject {
protected OptionalDoubleSubject(FailureMetadata metadata, OptionalDouble actual);
public void isPresent();
public void isEmpty();
public void hasValue(double expected);
}
/**
* Subject class for making assertions about Stream values.
*/
public class StreamSubject extends Subject {
/**
* Constructor for StreamSubject.
* @param metadata failure metadata for context
* @param actual the Stream under test
*/
protected StreamSubject(FailureMetadata metadata, Stream<?> actual);
/**
* Fails if the stream is not empty.
*/
public void isEmpty();
/**
* Fails if the stream is empty.
*/
public void isNotEmpty();
/**
* Fails if the stream does not have the given size.
* @param expectedSize the expected number of elements
*/
public void hasSize(int expectedSize);
/**
* Fails if the stream does not contain exactly the given elements.
* @param elements the expected elements
*/
public Ordered containsExactly(Object... elements);
/**
* Fails if the stream does not contain exactly the elements in the given iterable.
* @param expected the iterable containing expected elements
*/
public Ordered containsExactlyElementsIn(Iterable<?> expected);
}
/**
* Subject class for making assertions about IntStream values.
*/
public class IntStreamSubject extends Subject {
protected IntStreamSubject(FailureMetadata metadata, IntStream actual);
public void isEmpty();
public void isNotEmpty();
public void hasSize(int expectedSize);
public Ordered containsExactly(int... elements);
public Ordered containsExactlyElementsIn(Iterable<Integer> expected);
}
/**
* Subject class for making assertions about LongStream values.
*/
public class LongStreamSubject extends Subject {
protected LongStreamSubject(FailureMetadata metadata, LongStream actual);
public void isEmpty();
public void isNotEmpty();
public void hasSize(int expectedSize);
public Ordered containsExactly(long... elements);
public Ordered containsExactlyElementsIn(Iterable<Long> expected);
}
/**
* Interface returned by containsExactly methods to enforce ordering constraints.
*/
public interface Ordered {
/**
* Requires that the elements appear in the given order.
*/
void inOrder();
}Install with Tessl CLI
npx tessl i tessl/maven-com-google-truth--truth