Java 14 has finally been released, so The source code introduced in the previous Implementing Table Driven Test in Java, I rewrote it using Records added as a Preview in Java 14.
In the previous source code I kept the test cases in an inner class called TestCase. Constructors and getters were defined using Lombok.
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.experimental.Accessors;
import org.junit.jupiter.api.*;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
class MathTest {
@Nested
static class Pow {
@AllArgsConstructor
@Getter
@Accessors(fluent = true)
static class TestCase {
private String name;
private double x;
private double y;
private double expected;
}
@TestFactory
Stream<DynamicNode> testPow() {
return Stream.of(
new TestCase("pow(2,1)", 2, 1, 2),
new TestCase("pow(2,2)", 2, 2, 4),
new TestCase("pow(2,3)", 2, 3, 8),
new TestCase("pow(2,0)", 2, 0, 1),
new TestCase("pow(2,-1)", 2, -1, 0.5),
new TestCase("pow(2,+Inf)", 2, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY),
new TestCase("pow(2,-Inf)", 2, Double.NEGATIVE_INFINITY, 0),
new TestCase("pow(+Inf,2)", Double.POSITIVE_INFINITY, 2, Double.POSITIVE_INFINITY),
new TestCase("pow(-Inf,2)", Double.NEGATIVE_INFINITY, 2, Double.POSITIVE_INFINITY)
).map(testCase -> DynamicTest.dynamicTest(
testCase.name(),
() -> {
double result = Math.pow(testCase.x(), testCase.y());
assertEquals(testCase.expected(), result);
})
);
}
}
}
In this source code, Changed to keep test cases in record. By using record, I was able to reduce the amount of code compared to using Lombok.
import org.junit.jupiter.api.DynamicNode;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.TestFactory;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MathTest {
@Nested
static class Pow {
record TestCase(String name, double x, double y, double expected) {
}
@TestFactory
Stream<DynamicNode> testPow() {
return Stream.of(
new TestCase("pow(2,1)", 2, 1, 2),
new TestCase("pow(2,2)", 2, 2, 4),
new TestCase("pow(2,3)", 2, 3, 8),
new TestCase("pow(2,0)", 2, 0, 1),
new TestCase("pow(2,-1)", 2, -1, 0.5),
new TestCase("pow(2,+Inf)", 2, Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY),
new TestCase("pow(2,-Inf)", 2, Double.NEGATIVE_INFINITY, 0),
new TestCase("pow(+Inf,2)", Double.POSITIVE_INFINITY, 2, Double.POSITIVE_INFINITY),
new TestCase("pow(-Inf,2)", Double.NEGATIVE_INFINITY, 2, Double.POSITIVE_INFINITY)
).map(testCase -> DynamicTest.dynamicTest(
testCase.name(),
() -> {
double result = Math.pow(testCase.x(), testCase.y());
assertEquals(testCase.expected(), result);
})
);
}
}
}
We hope that you will continue to improve the source code using new features.
Recommended Posts