AutoParams Documentation

website·Indexed 30 days ago

https://autoparams.github.io

A 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.

Tokens
15.9K
Snippets
105
Records
120
Agent score
72%

What's inside AutoParams

  1. Populate objects using writable properties and setters

    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.
  2. Combine @MethodAutoSource with @Freeze for locked parameters

    The @MethodAutoSource annotation is compatible with @Freeze. This allows you to lock in specific values for certain parameters using @Freeze while 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"));
    }
  3. Repeat parameterized tests with @Repeat

    The @Repeat annotation 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);
    }
  4. Install autoparams-lombok extension

    Add the autoparams-lombok dependency 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")
  5. 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 @Test method with @AutoParams (or @AutoKotlinParams for 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);
    }
  6. 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 @ValueSource or @CsvSource, use the @AutoSource annotation on a @ParameterizedTest method. 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);
    }
  7. Use @CsvAutoSource to mix manual CSV values and random parameters

    The @CsvAutoSource annotation combines the functionality of @CsvSource and @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);
    }
  8. Install AutoParams using Gradle (Groovy and Kotlin)

    Add the autoparams dependency 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")
  9. Create a custom data generator by extending ObjectGeneratorBase

    To enforce business rules or tailor test data, create a custom generator by extending ObjectGeneratorBase<T>. You must override the generateObject method, which provides an ObjectQuery and a ResolutionContext. Use context.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);
        }
    }
  10. 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 @Freeze annotation 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 Mockito when().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());
    }
  11. Use @ValueAutoSource for parameterized tests with mixed data

    The @ValueAutoSource (or @ValueAutoKotlinSource for 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, and java.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"));
    }