AutoParams Documentation
website·Indexed 30 days ago
https://autoparams.github.ioA JUnit 5 extension for automatic test data generation in Java, inspired by AutoFixture. It provides capabilities for generating primitive types, complex objects, generic types, collections, and arrays. Features include customization via DSL and annotations like @Customization, @FreezeBy, and @ValueAutoSource, as well as extensions for Project Lombok, Mockito, and Kotlin. Supports versions 9.x, 10.x, and 11.x.
What's inside AutoParams
- AutoParams can set values on an object's writable properties via their setters. This behavior is particularly useful for legacy models or Data Transfer Objects (DTOs) that lack constructors covering all available fields, as it allows AutoParams to populate the object after it has been created using its default constructor.
Combine @MethodAutoSource with @Freeze for locked parameters
The@MethodAutoSourceannotation is compatible with@Freeze. This allows you to lock in specific values for certain parameters using@Freezewhile still using a factory method to dynamically populate others.@AllArgsConstructor @Getter public class ValueContainer { private final String value; } @ParameterizedTest @MethodAutoSource("factoryMethod") void testMethod(int arg1, @Freeze String arg2, ValueContainer arg3) { assertEquals("foo", arg3.getValue()); } static Stream<Arguments> factoryMethod() { return Stream.of(Arguments.of(16, "foo")); }Repeat parameterized tests with @Repeat
The@Repeatannotation specifies how many times a test should be executed. When used with parameterized sources (like@ValueAutoSource) or@AutoSource, AutoParams generates fresh random values for any unspecified parameters on every single run. For example, combining@ValueAutoSource(ints = {1, 2, 3})with@Repeat(5)results in 15 total executions.@ParameterizedTest @AutoSource @Repeat(10) void testMethod(int a, int b) { Calculator sut = new Calculator(); int actual = sut.add(a, b); assertEquals(a + b, actual); }Install autoparams-lombok extension
Add theautoparams-lombokdependency to your project to enhance AutoParams compatibility with Project Lombok, allowing for automatic object generation via Lombok builders.<!-- Maven --> <dependency> <groupId>io.github.autoparams</groupId> <artifactId>autoparams-lombok</artifactId> <version>11.3.1</version> </dependency> // Gradle (Groovy) testImplementation 'io.github.autoparams:autoparams-lombok:11.3.1' // Gradle (Kotlin) testImplementation("io.github.autoparams:autoparams-lombok:11.3.1")Install AutoParams 9.x using Gradle (Kotlin)
Add the followingtestImplementationline to yourbuild.gradle.ktsfile when using the Kotlin DSL.testImplementation("io.github.autoparams:autoparams:9.0.0")Generate automatic test data with @AutoParams
AutoParams is a JUnit 5 extension that eliminates manual test data boilerplate by automatically supplying generated values to test method parameters. To use it, annotate a@Testmethod with@AutoParams(or@AutoKotlinParamsfor Kotlin). The extension will then populate the method's parameters with generated data.@Test @AutoParams void testMethod(int a, int b) { Calculator sut = new Calculator(); int actual = sut.add(a, b); assertEquals(a + b, actual); }Generate arbitrary test data with @AutoSource
AutoParams allows you to automatically generate test arguments for parameterized methods in Java and Kotlin. Instead of manually defining values via@ValueSourceor@CsvSource, use the@AutoSourceannotation on a@ParameterizedTestmethod. AutoParams will automatically populate the method parameters with generated data.@ParameterizedTest @AutoSource void parameterizedTest(int a, int b) { Calculator sut = new Calculator(); int actual = sut.add(a, b); assertEquals(a + b, actual); }Use @CsvAutoSource to mix manual CSV values and random parameters
The@CsvAutoSourceannotation combines the functionality of@CsvSourceand@AutoSource. It allows you to provide CSV-formatted input values for the first set of parameters in a test method, while the remaining parameters are automatically populated with randomly generated values.@ParameterizedTest @CsvAutoSource({"16, foo"}) void testMethod(int arg1, String arg2, String arg3) { assertEquals(16, arg1); assertEquals("foo", arg2); assertNotEquals(arg2, arg3); }Install AutoParams using Gradle (Groovy and Kotlin)
Add theautoparamsdependency to your Gradle build script using the appropriate DSL syntax.// Gradle Groovy DSL testImplementation 'io.github.autoparams:autoparams:10.2.0'// Gradle Kotlin DSL testImplementation("io.github.autoparams:autoparams:10.2.0")Create a custom data generator by extending ObjectGeneratorBase
To enforce business rules or tailor test data, create a custom generator by extendingObjectGeneratorBase<T>. You must override thegenerateObjectmethod, which provides anObjectQueryand aResolutionContext. Usecontext.resolve()to generate supporting values for the object's fields.public class ProductGenerator extends ObjectGeneratorBase<Product> { @Override protected Product generateObject(ObjectQuery query, ResolutionContext context) { UUID id = context.resolve(); String name = context.resolve(); ThreadLocalRandom random = ThreadLocalRandom.current(); BigDecimal priceAmount = new BigDecimal(random.nextInt(10, 10000 + 1)); return new Product(id, name, priceAmount); } }Generate Mockito test doubles with AutoParams
To automatically generate Mockito-based test doubles for interfaces and abstract classes, use the
@Customization(MockitoCustomizer.class)annotation on your test method.Combine this with the
@Freezeannotation to ensure that the same mock instance is injected into both the test method and the system under test (SUT) that depends on it. This allows you to configure the mock's behavior using standard Mockitowhen().thenReturn()syntax.public interface Dependency { String getName(); } public class SystemUnderTest { private final Dependency dependency; public SystemUnderTest(Dependency dependency) { this.dependency = dependency; } public String getMessage() { return "Hello " + dependency.getName(); } } @Test @AutoParams @Customization(MockitoCustomizer.class) void testMethod(@Freeze Dependency stub, SystemUnderTest sut) { when(stub.getName()).thenReturn("World"); assertEquals("Hello World", sut.getMessage()); }Use @ValueAutoSource for parameterized tests with mixed data
The@ValueAutoSource(or@ValueAutoKotlinSourcefor Kotlin) annotation allows you to specify a set of literal values for a test parameter while letting AutoParams automatically generate the remaining parameters. This is similar to JUnit 5's@ValueSource. It requires parameter names to be available at runtime. Supported literal types include:short,byte,int,long,float,double,char,boolean,java.lang.String, andjava.lang.Class.@ParameterizedTest @ValueAutoSource(strings = { "Camera", "Candle" }) void testMethod(String name, Factory<Product> factory) { Product product = factory.get( freezeArgument("name").to(name) ); assertTrue(product.getName().startsWith("Ca")); }