Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

AutoParams

> 后端框架
Open source

AutoParams is a versatile test data generator designed for parameterized tests in Java and Kotlin.

368 stars0 likes1 views
WebsiteGitHub

About

AutoParams is a versatile test data generator designed for parameterized tests in Java and Kotlin.

AutoParams

AutoParams is a JUnit 5 extension for automatic test data generation, inspired by AutoFixture.

Manually creating test data is often repetitive and distracts from the core logic of the test. AutoParams eliminates this boilerplate by supplying automatically generated values to your test method parameters, allowing you to write concise and focused tests.

Getting started is simple: annotate your @Test method with @AutoParams, and the parameters will be populated with generated data.

java
@Test
@AutoParams
void testMethod(int a, int b) {
    Calculator sut = new Calculator();
    int actual = sut.add(a, b);
    assertEquals(a + b, actual);
}

In the example above, a and b are automatically generated, making the test cleaner and reducing the need for manual setup or value triangulation.

AutoParams also supports more advanced scenarios. When multiple generated values need to share a reference—such as reviews referring to the same product—you can use the @Freeze annotation to ensure consistency.

java
@AllArgsConstructor
@Getter
public class Product {

    private final UUID id;
    private final String name;
    private final BigDecimal priceAmount;
}
java
@AllArgsConstructor
@Getter
public class Review {

    private final UUID id;
    private final UUID reviewerId;
    private final Product product;
    private final int rating;
    private final String comment;
}
java
@Test
@AutoParams
void testMethod(@Freeze Product product, Review[] reviews) {
    for (Review review : reviews) {
        assertSame(product, review.getProduct());
    }
}

This ensures that all generated Review instances refer to the same frozen Product, simplifying test setup in scenarios involving shared dependencies.

Requirements

  • JDK 1.8 or higher

Install

Maven

For Maven, you can add the following dependency to your pom.xml:

xml

  io.github.autoparams
  autoparams
  11.3.2

Gradle

For Gradle, use:

groovy
testImplementation 'io.github.autoparams:autoparams:11.3.2'

Features

AutoParams provides a set of features designed to make your tests more expressive and reduce repetitive setup. Here are some of its key capabilities:

@FreezeBy Annotation

The @FreezeBy annotation enables fine-grained control over value freezing in tests. It allows you to freeze a single value and reuse it across multiple generation targets that match specific conditions, such as type or name. This helps improve test readability and ensures consistency among generated values.

Matching Strategies

AutoParams provides several matching strategies that determine which targets should receive the frozen value during object generation. The following examples illustrate some strategies:

  • EXACT_TYPE

    Reuses the frozen value for all targets with the exact same type.

    java
    @AllArgsConstructor
    @Getter
    public class StringContainer {
    
        private final String value;
    }
    java
    import static autoparams.customization.Matching.EXACT_TYPE;
    
    public class TestClass {
    
        @Test
        @AutoParams
        void testMethod(
            @FreezeBy(EXACT_TYPE) String s1,
            String s2,
            StringContainer container
        ) {
            assertSame(s1, s2);
            assertSame(s1, container.getValue());
        }
    }

    In this example, all String targets—including the String field inside StringContainer—are generated with the same frozen value.

  • IMPLEMENTED_INTERFACES

    Reuses the frozen value for targets whose types are interfaces that the frozen value's type implements.

    java
    import static autoparams.customization.Matching.IMPLEMENTED_INTERFACES;
    
    public class TestClass {
    
        @Test
        @AutoParams
        void testMethod(
            @FreezeBy(IMPLEMENTED_INTERFACES) String s1,
            CharSequence chars,
            StringContainer container
        ) {
            assertSame(s1, chars);
            assertNotSame(s1, container.getValue());
        }
    }

    In this example, String implements CharSequence, so the same value is reused for both s1 and chars. StringContainer is not affected because its type is not an interface.

  • PARAMETER_NAME

    Reuses the frozen value for other targets with matching names.

    java
    import static autoparams.customization.Matching.PARAMETER_NAME;
    
    public class TestClass {
    
        @Test
        @AutoParams
        void testMethod(
            @FreezeBy(PARAMETER_NAME) UUID reviewerId,
            Review review
        ) {
            assertNotSame(reviewerId, review.getId());
            assertSame(reviewerId, review.getReviewerId());
        }
    }

    This strategy is useful when names follow a consistent convention that reflects their role.

You can also combine multiple matching strategies to broaden the scope of freezing.

java
import static autoparams.customization.Matching.EXACT_TYPE;
import static autoparams.customization.Matching.IMPLEMENTED_INTERFACES;

public class TestClass {

    @Test
    @AutoParams
    void testMethod(
        @FreezeBy({ EXACT_TYPE, IMPLEMENTED_INTERFACES }) String s1,
        String s2,
        CharSequence chars
    ) {
        assertSame(s1, s2);
        assertSame(s1, chars);
    }
}

In this example, the frozen value s1 is reused for both s2 (same type) and chars (interface implemented by String).

Shorthand for EXACT_TYPE

Using @Freeze is equivalent to @FreezeBy(EXACT_TYPE). It's a convenient shorthand for the most common matching strategy.

java
@Test
@AutoParams
void testMethod(@Freeze String s1, String s2) {
    assertSame(s1, s2);
}

Setting the Range of Values

You can constrain the range of automatically generated values using the @Min and @Max annotations. These let you define minimum and maximum bounds for numeric parameters, ensuring that generated values fall within a specified range.

To apply a range, annotate the parameter with @Min and/or @Max as needed.

Here's an example:

java
@Test
@AutoParams
void testMethod(@Min(1) @Max(10) int value) {
    assertTrue(value >= 1);
    assertTrue(value ` class

The `Factory` class is useful when you need to generate multiple instances of the same type. It allows you to create single instances or collections of generated objects on demand.

Here's an example:

```java
@Test
void testMethod() {
    Factory factory = Factory.create(Product.class);
    Product product = factory.get();
    List products = factory.getRange(10);
}

…

java
@Test
@AutoParams
void testMethod(@Size(min = 5) ArrayList arrayList) {
    assertThat(arrayList).hasSize(5);
}
java
@Test
@AutoParams
void testMethod(@Size(min = 5) String[] array) {
    assertThat(array).hasSize(5);
}

…

java
public class ProductGenerator extends ObjectGeneratorBase {

    @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);
    }
}

This custom generator creates a Product instance that adheres to the business constraints. It uses ResolutionContext to generate supporting values like id and name, and applies explicit logic to generate a valid priceAmount.

You can apply this custom generator using the @Customization annotation:

java
@Test
@AutoParams
@Customization(ProductGenerator.class)
void testMethod(Product product) {
    assertTrue(product.getPriceAmount().compareTo(BigDecimal.valueOf(10)) >= 0);
    assertTrue(product.getPriceAmount().compareTo(BigDecimal.valueOf(10000))  {

    @Override
    protected Review generateObject(ObjectQuery query, ResolutionContext context) {
        UUID id = context.resolve();
        UUID reviewerId = context.resolve();
        Product product = context.resolve();
        String comment = context.resolve();

        ThreadLocalRandom random = ThreadLocalRandom.current();
        int rating = random.nextInt(1, 5 + 1);

        return new Review(id, reviewerId, product, rating, comment);
    }
}
java
@Test
@AutoParams
@Customization({ ProductGenerator.class, ReviewGenerator.class })
void testMethod(Product product, Review review) {
    assertTrue(product.getPriceAmount().compareTo(BigDecimal.valueOf(10)) >= 0);
    assertTrue(product.getPriceAmount().compareTo(BigDecimal.valueOf(10000)) = 1);
    assertTrue(review.getRating() = 0);
    assertTrue(product.getPriceAmount().compareTo(BigDecimal.valueOf(10000)) = 1);
    assertTrue(review.getRating() = 0);
    assertTrue(product1.getPriceAmount().compareTo(BigDecimal.valueOf(10000)) `.

```java
import static autoparams.customization.dsl.ArgumentCustomizationDsl.set;

public class TestClass {

    @Test
    @AutoParams
    void testMethod(Product product, @Max(5) int rating, Factory factory) {
        Review review = factory.get(
            set(Review::getProduct).to(product),
            set(Review::getRating).to(rating)
        );
        assertSame(product, review.getProduct());
        assertEquals(rating, review.getRating());
    }
}

The Factory class provides a convenient way to create customized objects when working with a single type. It avoids managing an explicit resolution context and keeps the test focused on the instances under test.

Note
The set method relies on the availability of parameter names at runtime. However, Java does not include parameter names in bytecode by default. To ensure this works correctly, you can:

  1. Use a record class, which preserves parameter names by design.
  2. Compile with the -parameters option when using javac, or -java-parameters when using kotlinc.
    If you're using Spring Boot, this option is automatically enabled when you use the Spring Boot Gradle plugin or the Spring Boot Maven plugin.
  3. Apply the @ConstructorProperties annotation to constructors to explicitly declare parameter names.
    This annotation works only for constructors and has no effect on regular methods. If you're using Lombok and the constructor is generated by a Lombok annotation such as @AllArgsConstructor, the @ConstructorProperties annotation can be automatically added by enabling the lombok.anyConstructor.addConstructorProperties = true option.
    For more details, see: https://projectlombok.org/features/constructor

Settable Properties

If a class follows the JavaBeans convention—meaning it has a no-arguments constructor and public setter methods—AutoParams can automatically populate its properties using the InstancePropertyWriter customizer.

Here's a simple example:

java
@Getter
@Setter
public class User {

    private Long id;
    private String name;
}

By applying the InstancePropertyWriter customizer, AutoParams will generate and assign values to the id and name properties automatically:

java
@Test
@AutoParams
@Customization(InstancePropertyWriter.class)
void testMethod(User user) {
    assertNotNull(user.getId());
    assertNotNull(user.getName());
}

In this test, the User object is created using its default constructor, and AutoParams sets values on its writable properties via their setters. This is especially useful when working with legacy models or data transfer objects(DTOs) that do not have constructors covering all fields.

Logging for Object Resolution

AutoParams provides detailed logging capabilities that help you understand how objects are being resolved during test execution. To enable logging, apply the @LogResolution annotation to your test method alongside @AutoParams. When enabled, the resolution log is printed to stan

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Javajavajunit5kotlinspring

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架