Skip to content

Commit

Permalink
Added more tests and lazy logging demo
Browse files Browse the repository at this point in the history
  • Loading branch information
kousen committed Aug 14, 2024
1 parent b957254 commit 28bbf68
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
33 changes: 32 additions & 1 deletion src/test/java/lambdas/FileFilterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

@DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
public class FileFilterTest {
Expand Down Expand Up @@ -39,6 +41,13 @@ void listDirectories_expressionLambda() {
assertEquals(14, directories.length);
}

@Test
void listDirectories_method_reference() {
File[] directories = root.listFiles(File::isDirectory);
assert directories != null;
assertEquals(14, directories.length);
}

@Test
void listDirectories_blockLambda() {
File[] directories = root.listFiles(path -> {
Expand All @@ -55,4 +64,26 @@ void list_directories_assigned_to_variable() {
assert directories != null;
assertEquals(14, directories.length);
}

@Test
void expect_exception() {
String x = null;
Exception ex = assertThrows(NullPointerException.class,
() -> x.length());
System.out.println(ex.getMessage());
}

@Test
void list_directories_java_src_files_filenamefilter() {
File[] directories = root.listFiles((dir, name) -> name.endsWith(".java"));
assertNotNull(directories);
assertEquals(8, directories.length);
}

@Test
void list_directories_java_src_files_filefilter() {
File[] directories = root.listFiles(path -> path.getName().endsWith(".java"));
assertNotNull(directories);
assertEquals(8, directories.length);
}
}
10 changes: 10 additions & 0 deletions src/test/java/lambdas/LazyErrorMessageTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,34 @@

import org.junit.jupiter.api.Test;

import java.util.logging.Logger;

import static org.junit.jupiter.api.Assertions.assertTrue;

public class LazyErrorMessageTest {
private final Logger log = Logger.getLogger(this.getClass().getName());

private String getErrorMessage() {
System.out.println("Generating error message...");
return "x should be true";
}

private String getLogMessage() {
System.out.println("Generating log message...");
return "x should be true";
}

@Test
void assertArgIsTrue() {
boolean x = true;
assertTrue(x, getErrorMessage()); // 2nd arg is a String
log.fine(getLogMessage());
}

@Test
void assertArgIsTrue_lazyErrorMessage() {
boolean x = true;
assertTrue(x, () -> getErrorMessage()); // 2nd arg is a Supplier<String>
log.fine(() -> getLogMessage());
}
}

0 comments on commit 28bbf68

Please sign in to comment.