Skip to content

Instantly share code, notes, and snippets.

package com.tom;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class FuncTypeSafeMatcher<T> extends TypeSafeMatcher<T> {
public class StoryTest3 {
@Test
public void shouldReturnHobbitCharacters() {
List<Character> characters = new TestCharacterData().fellowshipOfTheRing();
Story story = Story.builder().characters(characters).build();
Set<Character> fellowshipOfRingHobbits = story.charactersOf(Race.HOBBIT);
assertThat(fellowshipOfRingHobbits).containsOnly(FRODO, SAM, MERRY, PIPPIN)
.extracting(Character::getRace)
.containsOnly(Race.HOBBIT);
}
public class StoryTest2 {
@Test
public void shouldReturnHobbitCharacters() {
List<Character> characters = Arrays.asList(BILBO, SAM, ARAGORN, GANDALF, FRODO);
Story story = Story.builder().characters(characters).build();
Set<Character> storyHobbits = story.charactersOf(Race.HOBBIT);
assertThat(storyHobbits).containsOnly(BILBO, FRODO, SAM)
.extracting(Character::getRace)
.containsOnly(Race.HOBBIT);
}
public class StoryTest1 {
@Test
public void shouldReturnHobbitCharacters() {
List<Character> characters = new TestCharacterData().createList();
Story story = Story.builder().characters(characters).build();
Set<Character> storyHobbits = story.charactersOf(Race.HOBBIT);
assertThat(storyHobbits).containsOnly(BILBO, FRODO, SAM)
.extracting(Character::getRace)
.containsOnly(Race.HOBBIT);
}
// Product class
public Integer getPackageQuantity2() {
return firstNonNull(quantity, innerPackQuantity, DEFAULT_QUANTITY);
}
// Utils class
public static <T> T firstNonNull(T... args) {
return Stream.of(args)
.filter(Objects::nonNull)
.findFirst()
public Integer getPackageQuantity() {
return ObjectUtils.firstNonNull(quantity, innerPackQuantity, DEFAULT_QUANTITY);
}
import static java.util.Objects.requireNonNull;
...
// throws a NullPointerException when null
requireNonNull(employee);
// throws a NullPointerException with a message
requireNonNull(employee, "employee reference is null");
// throws a NullPointerException with a message from a supplier function
public void generatePaycheck(@NonNull Employee employee) {
// do paycheck stuff ...
}
public void optionalCreationExamples() {
// city can be null
Optional<City> optionalCity = Optional.ofNullable(city);
// cannot be null or NullPointerException is thrown
Optional<City> presentCity = Optional.of(city);
// creates a empty or not present instance of optional
Optional<City> absentCity = Optional.empty();
public void validateCity(String cityCode) {
Optional<City> city = findCity(cityCode);
if (city.isPresent()) {
return;
}
setError(CITY_INVALID, cityCode);
}
public Optional<City> findCity(String cityCode) {
City city = cityRepository.get(cityCode);