Last active
December 6, 2025 08:01
-
-
Save benjiman/e9f2904a2d875974dfef3f14f4083d5d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.benjiweber.example; | |
| import org.junit.jupiter.api.extension.ExtensionContext; | |
| import org.junit.jupiter.params.ParameterizedTest; | |
| import org.junit.jupiter.params.provider.Arguments; | |
| import org.junit.jupiter.params.provider.ArgumentsProvider; | |
| import org.junit.jupiter.params.provider.ArgumentsSource; | |
| import java.util.Arrays; | |
| import java.util.List; | |
| import java.util.stream.Stream; | |
| import static org.junit.jupiter.api.Assertions.assertEquals; | |
| public class ExampleRecordParameterizedTest { | |
| public record MyTestData(String name, Integer age) {} | |
| static class MyTestDataValues implements SourceOf<MyTestData> { | |
| public List<MyTestData> values() { | |
| return List.of( | |
| new MyTestData("foo", 5), | |
| new MyTestData("bar", 10) | |
| ); | |
| } | |
| } | |
| @ParameterizedTest(name="{0} - {1}") | |
| @ArgumentsSource(MyTestDataValues.class) | |
| public void exampleTest(String name, Integer age) { | |
| System.out.println(name + " " + age); | |
| assertEquals(0, age % 5); | |
| assertEquals(3, name.length()); | |
| } | |
| public interface SourceOf<T extends Record> extends ArgumentsProvider { | |
| List<T> values(); | |
| default Stream<? extends Arguments> provideArguments(ExtensionContext context) throws Exception { | |
| return values().stream().map(v -> Arrays.stream(v.getClass().getRecordComponents()).map(rc -> { | |
| try { | |
| return rc.getAccessor().invoke(v); | |
| } catch (Exception e) { | |
| throw new RuntimeException(e); | |
| } | |
| }).toArray()).map(Arguments::of); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment