Arbitrary test data generator for parameterized tests in Java inspired by AutoFixture.

Overview

AutoParams

CI Publish

AutoParams is an arbitrary test data generator for parameterized tests in Java inspired by AutoFixture.

Sometimes setting all the test data manually is very annoying. Sometimes some test data is required but not that important for a particular test. AutoParams automatically generates test arguments for your parameterized test method so you can focus more on your domain and your requirements.

AutoParams is very easy to use. Just decorate your parameterized test method with @AutoSource annotation just like using @ValueSource annotation or @CsvSource annotation. That's all. Then AutoParams wiil generate arbitrary arguments for the parameters of the test method automatically.

@ParameterizedTest
@AutoSource
void parameterizedTest(int a, int b) {
    Calculator sut = new Calculator();
    int actual = sut.add(a, b);
    assertEquals(a + b, actual);
}

In the example above, you can see that the arbitrary test data may eliminate the need for triangulation from tests.

Requirements

  • JDK 1.8 or higher

Install

Maven

<dependency>
  <groupId>io.github.javaunit</groupId>
  <artifactId>autoparams</artifactId>
  <version>0.1.2</version>
</dependency>

Gradle

testImplementation 'io.github.javaunit:autoparams:0.1.2'

Features

Primitive Types

AutoParams generates arbitrary test arguments of primitive types.

@ParameterizedTest
@AutoSource
void testMethod(boolean x1, int x2, long x3, float x4, double x5, char x6) {
}

Simple Objects

AutoParams generates arbitrary simple objects for the test parameters.

@ParameterizedTest
@AutoSource
void testMethod(String x1, UUID x2, BigInteger x3) {
}

Enum Types

Enum types are also supported. AutoParams randomly selects enum values.

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY
}

@ParameterizedTest
@AutoSource
void testMethod(Day day) {
}

Complex Objects

AutoParams creates complex objects using a public constructor with arbitrary arguments. If the type has more than one public constructors, AutoParams chooses the constructor with the fewest parameters.

class ComplexObject {

    private final int value1;
    private final String value2;

    public ComplexObject(int value1, String value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    public int getValue1() {
        return value1;
    }

    public String getValue2() {
        return value2;
    }

}

@ParameterizedTest
@AutoSource
void testMethod(ComplexObject object) {
}

Constructor Selection Policy

When AutoParams creates objects of complex types it follows the following rules.

  1. The constructor decorated with @ConstructorProperties annotation is preferentially selected.
  2. AutoParams selects the constructor with the fewest parameters.
class ComplexObject {

    private final int value1;
    private final String value2;
    private final UUID value3;

    @ConstructorProperties({"value1", "value2, value3"})
    public ComplexObject(int value1, String value2, UUID value3) {
        this.value1 = value1;
        this.value2 = value2;
        this.value3 = value3;
    }

    @ConstructorProperties({"value1", "value2"})
    public ComplexObject(int value1, String value2) {
        this(value1, value2, null);
    }

    public ComplexObject(int value1) {
        this(value1, null, null);
    }

    public int getValue1() {
        return value1;
    }

    public String getValue2() {
        return value2;
    }

    public UUID getValue3() {
        return value3;
    }

}

@ParameterizedTest
@AutoSource
void testMethod(ComplexObject object) {
    assertNotNull(object.getValue2());
    assertNull(object.getValue3());
}

Generic Types

AutoParams creates objects of generic type using a public constructor with arbitrary arguments. If the type has more than one public constructors, AutoParams chooses the constructor with the fewest parameters.

class GenericObject<T1, T2> {

    private final T1 value1;
    private final T2 value2;

    public GenericObject(T1 value1, T2 value2) {
        this.value1 = value1;
        this.value2 = value2;
    }

    public T1 getValue1() {
        return value2;
    }

    public T2 getValue2() {
        return value3;
    }

}

@ParameterizedTest
@AutoSource
void testMethod(
    GenericObject<String, ComplexObject> object1,
    GenericObject<UUID, GenericObject<String, ComplexObject>> object2) {
}

Collection Types

AutoParams supports a variety of collection types and streams.

Arrays

AutoParams generates an array instance with three elements.

@ParameterizedTest
@AutoSource
void testMethod(int[] array1, String[] array2) {
}

List Types

List<E> interface and ArrayList<E> class supported. Generated list objects contain few elements.

@ParameterizedTest
@AutoSource
void testMethod(List<String> list, ArrayList<UUID> arrayList) {
}

Set Types

Set<E> interface and HashSet<E> class supported. Generated set objects contain few elements.

@ParameterizedTest
@AutoSource
void testMethod(Set<String> set, HashSet<UUID> hashSet) {
}

Map Interface

Map<K, V> interface and HashMap<K, V> class supported. Generated map objects contain few pairs.

@ParameterizedTest
@AutoSource
void testMethod(Map<String, ComplexObject> map, HashMap<UUID, ComplexObject> hashMap) {
}

Streams Types

Generic Stream Interface

AutoParams supports the generic Stream<T> interface. Generated stream objects provide few elements.

@ParameterizedTest
@AutoSource
void testMethod(Stream<ComplexObject> stream) {
}

Stream Interfaces of Primitive Types

Stream Interfaces specific to primitive types are supported.

@ParameterizedTest
@AutoSource
void testMethod(IntStream intStream, LongStream longStream, DoubleStream doubleStream) {
}

Repeat

Unit tests can be repeated with arbitrary test data. Set repeat property of @AutoSource annotation as many times as you want to repeat.

@ParameterizedTest
@AutoSource(repeat = 10)
void testMethod(int a, int b) {
    // This test method is performed ten times.
    Calculator sut = new Calculator();
    int actual = sut.add(a, b);
    assertEquals(a + b, actual);
}
Comments
  • 기본 생성자 런타임 피드백

    기본 생성자 런타임 피드백

    클래스가 매개변수가 없는 기본 생성자를 포함해 여러 개의 공개(public) 생성자를 가질 때 #43 논리에 의해 기본 생성자가 선택되는데, 프레임워크에 의해 기본 생성자가 유도된 상황이라면 AutoParams가 기본 생성자를 선택하는 것은 바람직하지 않을 수 있다.

    이 때 런타임 피드백(예외)를 제공할 필요가 있는지 논의할 필요가 있다.

    question 
    opened by gyuwon 21
  • checkstyle 및 formatter 설정

    checkstyle 및 formatter 설정

    • checkstyle 및 formatter 설정에 대해 논의합니다.
    • 우선 checkstyle 및 formatter 가 필요할지에 대해 의견 부탁드립니다.
      • checkstyle 은 gradle 로 검사할 수 있지만, checkstyle 에 맞는 formatter 를 셋팅하는건 간단하지만은 않습니다.
      • 보통 Intellij formatter 로 맞추지만 vs code 등 다른 툴을 호환하려면 각 툴에 맞는 formatter 가 각각 정의되어야 합니다.
    enhancement 
    opened by mhyeon-lee 21
  • Parameter 예외 케이스 지원

    Parameter 예외 케이스 지원

    #101 문제 상황이 재현이 되지 않습니다.

    Spring Bean은 interface, abstract class type도 Bean으로 등록이 되는데요. autoparams는 interface와 abstract이 지원되는 타입이 아닌 상황입니다.

    Spring Autowired와 호환될 수 있도록 파라미터에 애노테이션이 있다면 예외 상황으로써 다른 동작이 될 수 있도록 하는게 어떨까요?

    question 
    opened by Rebwon 16
  • 테스트에서 package-private 제품코드 접근 방지

    테스트에서 package-private 제품코드 접근 방지

    다음과 그림과 같이 테스트 패키지 이름을 제품 코드랑 구분해서 package-private 제품코드 접근 방지하는 것에 대해 논의를 해보려고 이슈를 만듭니다. 넌센스일까요?

    image

    @mhyeon-lee 님이 https://github.com/JavaUnit/AutoParams/pull/83#discussion_r598237623 에서 org.javaunit.autopararms.test 이름을 얘기해주셨습니다.

    enhancement 
    opened by jwChung 14
  • builder fix 기능 구현

    builder fix 기능 구현

    아래 시나리오와 같이 특정 타입 범위 안에서 값을 고정 시키는 기능을 구현한다.

    이 이슈는 특정 타입 범위란 점에서 #15(테스트 메소드 범위)와 차이를 보이며, #3 custom API 의 사용자 시나리오이다.

    @ParameterizedTest
    @AutoSource
    public void test(Builder<Bar> barBuilder) {
        Bar bar = barBuilder.fix(int.class, 123).build();
    
        // bar.value == 123
        // bar.getFoo().getValues() == [123, 123, 123]
    }
    
    public class Foo {
        private final int[] values;
    
        public Foo(int[] values) {
            this.values = values;
        }
    
        ...
    }
    
    public class Bar {
        Foo foo;
        int value;
    
        public Bar(Foo foo, int value) {
            this.foo = foo;
            this.value = value;
        }
    
        ...
    }
    
    
    enhancement 
    opened by jwChung 13
  • LocalDateTime, LocalDate 타입 지원이 필요합니다.

    LocalDateTime, LocalDate 타입 지원이 필요합니다.

    @ParameterizedTest
    @AutoSource
    void testWithLocalDateTime(LocalDateTime localDateTime) {
    }
    
    @ParameterizedTest
    @AutoSource
    void testWithLocalDate(LocalDate localDate) {
    }
    

    LocalDateTime, LocalDate는 현재 날짜, 시각을 반환해야 합니다. LocalDateTime, LocalDate는 범위를 지정할 수 있어야 합니다.

    enhancement 
    opened by Rebwon 12
  • ObjectGenerator generate 의 지원하지 않음과 null 반환을 구분

    ObjectGenerator generate 의 지원하지 않음과 null 반환을 구분

    현재 ObjectGenerator 는 아래와 같이 Optional 을 반환하는 generate 메소드가 제공됩니다.

    interface ObjectGenerator {
    
        Optional<Object> generate(ObjectQuery query, ObjectGenerationContext context);
    
    }
    

    Generator 구현체가 ObjectQuery 의 지원 대상이 아니라면 Optional.empty 를 반환합니다. Generator 가 null 을 반환할 수 있다면 지원하지 않음null 반환을 구분할 필요가 생깁니다.

    우선 아래 2가지 중에 하나를 선택할 수 있을거 같은데요. 더 나은 방법이 있을까요? 의견 부탁드립니다.

    1. ObjectGenerator 가 ObjectQuery 지원 가능을 판단하는 API 를 추가한다.
    2. generate 가 ObjectQuery 를 지원하지 않는다면, Exception 을 던진다.

    Tasks

    • [x] GenerationResult 타입 도입
    • [x] 모든 generator GenerationResult generateObject(...) 구현
    • [x] 모든 generator에서 Optional<Object> generate(...) 메소드 삭제
    • [x] generateObject -> generate 로 메소드 이름 변경
    enhancement 
    opened by mhyeon-lee 11
  • 매개변수 수가 가장 적은 생성자 선택 논리 구현

    매개변수 수가 가장 적은 생성자 선택 논리 구현

    README.md 파일에 다음 문구가 있지만 실제론 구현되지 않는다.

    If the type has more than one public constructors, AutoParams chooses the constructor with the fewest parameters.

    bug 
    opened by gyuwon 11
  • JavaBeans 스펙 객체 생성 전략 옵션 지원

    JavaBeans 스펙 객체 생성 전략 옵션 지원

    • JavaBeans 스펙의 객체 생성을 지원합니다.
    • Spec
      • No Args Constructor 로 객체를 생성한 후 setter 메소드로 값을 주입한다.
      • No Args Constructor 는 public 접근자이다.
      • setter 메소드명은 set 으로 시작한다.
      • 반환형은 void 이다.
      • 매개변수는 1개 또는 2개를 가진다.
        • Indexed property 인 경우 2개이며, 첫번째 매개변수는 int 형이다.
    스크린샷 2021-05-04 오전 1 55 43
    // sample
    PropertyDescriptor[] descriptors = Introspector.getBeanInfo(JsonSerializeObject.class).getPropertyDescriptors();
    for (PropertyDescriptor descriptor : descriptors) {
        if (descriptor instanceof IndexedPropertyDescriptor) {
            Method method = ((IndexedPropertyDescriptor)descriptor).getIndexedWriteMethod();
            // method Invoke (index, value)
        } else {
            Method method = descriptor.getWriteMethod();
            // method invoke (value)
        }
    }
    
    • IndexedWriteMethod 와 WriteMethod 둘다 존재할 때 어떤 메소드를 선택할 것인가?
    enhancement 
    opened by mhyeon-lee 9
  • junit-jupiter-params 5.7.2 지원

    junit-jupiter-params 5.7.2 지원

    오류 내용

    @CsvAutoSource를 사용하면 다음과 같은 오류가 발생합니다.

    Receiver class org.javaunit.autoparams.CsvAutoArgumentsProvider$1 does not define or inherit an implementation of the resolved method 'abstract int maxCharsPerColumn()' of interface org.junit.jupiter.params.provider.CsvSource.
    

    오류 원인

    아래 명령어를 사용하여 의존 그래프를 확인하면, autoparams 패키지는 junit-jupiter-params은 5.7.2 버전을 사용합니다.

    $ ./gradlew <프로젝트명>:dependencies
    
    \--- io.github.javaunit:autoparams:0.2.8
         +--- org.junit.jupiter:junit-jupiter-api:5.6.0 -> 5.7.2 (*)
         +--- org.junit.jupiter:junit-jupiter-params:5.6.0 -> 5.7.2 (*)
         +--- javax.validation:validation-api:2.0.1.Final
         \--- com.google.code.findbugs:jsr305:3.0.2
    
    1. javaunit:autoparams는 5.6.0을 사용하도록 설정되어있으나 의도치 않게 5.7.2가 사용됩니다

      https://github.com/JavaUnit/AutoParams/blob/05c33321821b5f660537a996ccad244e1150db68/autoparams/build.gradle#L7

    2. junit-jupiter-params 5.7.2 버전에서 @CsvSourceint maxCharsPerColumn() 메서드가 추가됐지만, AutoParams에서 이를 구현하지 않아 문제가 발생합니다. https://github.com/JavaUnit/AutoParams/blob/05c33321821b5f660537a996ccad244e1150db68/autoparams/src/main/java/org/javaunit/autoparams/CsvAutoArgumentsProvider.java#L29-L59

    opened by wplong11 8
  • ComplextObjectGenerator customize 방법 지원 필요

    ComplextObjectGenerator customize 방법 지원 필요

    • 특정 타입에 대한 Customize 를 끼워넣기 위해서는 Customizer 구현체에서 원하는 타입은 Customize 된 Generator 로 생성하도록 제어할 수 있습니다.
    • 그런데 ComplexObjectGenerator 의 generate 방식을 변경(Customize)하기 위한 방법이 없어 보입니다.
    • ComplexObjectGenerator 의 내부 객체 생성 방식을 Customize 할 수 있는 기능 제공이 필요할거 같습니다.

    좋은 방법이 있을까요?

    question 
    opened by mhyeon-lee 8
  • Add KotlinCustomizer for kotlin class constructor having default value

    Add KotlinCustomizer for kotlin class constructor having default value

    Purpose

    Solve the problem that ComplexObjectGenerator does not use primary constructor of kotlin class.

    Summary

    As in the code below, you can apply Kotlin settings using KotlinCustomizer Unlike PR #290, the core module does not reference Kotlin modules.

    @ParameterizedTest
    @AutoSource
    @Customization(KotlinCustomizer::class)
    fun sut_creates_with_primary_constructor(fixture: HavingDefaultValueForConstructorParameter) {
        val defaultValue = HavingDefaultValueForConstructorParameter()
        assertThat(fixture.value1).isNotEqualTo(defaultValue.value1)
        assertThat(fixture.value2).isNotEqualTo(defaultValue.value2)
        assertThat(fixture.value3).isNotEqualTo(defaultValue.value3)
    }
    
    data class HavingDefaultValueForConstructorParameter(
        val value1: String = "default value",
        val value2: List<Int> = emptyList(),
        val value3: Long = 0,
    )
    

    Review Guide

    • Please view the commits in order

    TODO

    • [ ] Add deployment settings for kotlin module
    • [ ] Documentation about Kotlin support (+Add troubleshooting guide about kotlin support)
    opened by wplong11 4
  • BigDecimal 타입 데이터의 범위 설정 지원

    BigDecimal 타입 데이터의 범위 설정 지원

    현재 @Min, @Max 로 Int, Long 타입 데이터의 범위 설정이 가능합니다.

    https://github.com/AutoParams/AutoParams#setting-the-range-of-values

    You can specify the range of arbitrary values using the @Min annotation and the @Max annotations.

    BigDecimal 타입에 대해서도 범위 설정 기능이 지원되면 좋을 것 같습니다.

    @Min, @Max의 인자 타입은 Long이기 때문에 @DecimalMin, @DecimalMax 어노테이션을 활용해야 할 것 같습니다

    opened by 33577 1
  • [kotlin] ObjectGenerationContext.generate 확장 메서드 추가

    [kotlin] ObjectGenerationContext.generate 확장 메서드 추가

    아래과 같은 코드를

    val foo: Long = context.generate { Long::class.java } as Long
    

    다음과 같이 작성할 수 있도록

    val foo: Long = context.generate()
    

    코틀린 확장 함수를 추가한다

    inline fun <reified T> ObjectGenerationContext.generate(): T {
        return this.generate { T::class.java } as T
    }
    
    opened by wplong11 0
  • kotlin class 에서 param생성 안됨

    kotlin class 에서 param생성 안됨

    아래와 같이 value parameter 를 명시한 class에서는

    class Hello(
         var value1: Int = 10,
         var value2: String = "Hello",
    )
    
    @ParameterizedTest
    @AutoSource
    fun testHello(data: Hello) {
        println(data)
    }
    
    Hello(value1=10, value2=Hello)
    

    이렇게 auto source가 적용이 안되어 동작이 안되는 문제가 있습니다.

    class Hello(
         var value1: Int, //여기
         var value2: String = "Hello",
    )
    

    하지만, parameter값을 하나라도 assign하지 않으면 잘 동작합니다.

    Hello(value1=-375170361, value2=869a50ed-6b97-4eab-896e-add4df1e4fc9)
    

    parameter value 가 assign된 class라도 auto param이 적용되어야 할것 같은데.. 어떤 이유에서 이런 동작이 되는지 잘 이해가 안되네요 ㅠㅠ 확인 가능할까요?

    opened by issess 16
  • Support java.time.Instant type

    Support java.time.Instant type

    https://github.com/JavaUnit/AutoParams/issues/70

    • Add java.time.Instant type generator
    • Refactor some generators which are related to java.time package to use InstantGenerator and ZoneIdGenerator for fixing value.
      • ClockGenerator, OffsetDateTimeGenerator, ZonedDateTimeGenerator
    opened by sshplendid 1
Releases(1.1.1)
Owner
null
A simple yet powerful parameterized test runner for Java.

TestParameterInjector Introduction TestParameterInjector is a JUnit4 test runner that runs its test methods for different combinations of field/parame

Google 324 Dec 30, 2022
A BDD-style test runner for Java 8. Inspired by Jasmine, RSpec, and Cucumber.

Spectrum A colorful BDD-style test runner for Java Spectrum is inspired by the behavior-driven testing frameworks Jasmine and RSpec, bringing their ex

Greg Haskins 143 Nov 22, 2022
Never debug a test again: Detailed failure reports and hassle free assertions for Java tests - Power Asserts for Java

Scott Test Reporter for Maven and Gradle Get extremely detailed failure messages for your tests without assertion libraries, additional configuration

Dávid Csákvári 133 Nov 17, 2022
A sample repo to help you handle basic auth for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to handle basic auth for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - htt

null 12 Jul 13, 2022
A sample repo to help you run automation test in incognito mode in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to run automation test in incognito mode in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - htt

null 12 Jul 13, 2022
A sample repo to help you handle cookies for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to handle cookies for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - https:

null 13 Jul 13, 2022
A sample repo to help you set geolocation for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to set geolocation for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows - https

null 12 Jul 13, 2022
A sample repo to help you capture JavaScript exception for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to capture JavaScript exception for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Wi

null 12 Jul 13, 2022
A sample repo to help you find an element by text for automation test in Java-selenium on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to find an element by text for automation test in Java-selenium on LambdaTest Prerequisites Install and set environment variable for java. Windows

null 12 Jul 13, 2022
A sample repo to help you emulate network conditions in Java-selenium automation test on LambdaTest. Run your Java Selenium tests on LambdaTest platform.

How to emulate network conditions in Java-selenium automation test on LambdaTest Prerequisites Install and set environment variable for java. Windows

null 12 Jul 13, 2022
PGdP-Tests-WS21/22 is a student-created repository used to share code tests.

PGdP-Tests-WS21-22 PGdP-Tests-WS21/22 is a student-created repository used to share code tests. Important Note: In the near future, most exercises wil

Jonas Ladner 56 Dec 2, 2022
🤖 Unleash the full power of test.ai into your Java Selenium tests

The test.ai selenium SDK is a simple library that makes it easy to write robust cross-browser web tests backed by computer vision and artificial intelligence.

test.ai 5 Jul 15, 2022
🤖 Unleash the full power of test.ai into your Java Appium tests

The test.ai Appium SDK is a simple library that makes it easy to write robust cross-platform mobile application tests backed by computer vision and ar

test.ai 9 Jun 4, 2022
A sample repo to help you capture JavaScript exception for automation test in Java-TestNG on LambdaTest. Run Selenium tests with TestNG on LambdaTest platform.

How to capture JavaScript exception for automation test in Java-TestNG on LambdaTest Environment Setup Global Dependencies Install Maven Or Install Ma

null 11 Jul 13, 2022
A sample repo to help you use relative locators for automation test in Java-TestNG on LambdaTest. Run Selenium tests with TestNG on LambdaTest platform.

How to use relative locators for automation test in Java-TestNG on LambdaTest Environment Setup Global Dependencies Install Maven Or Install Maven wit

null 11 Jul 13, 2022
A sample repo to help you use CDP console in Java-TestNG automation test on LambdaTest. Run Selenium tests with TestNG on LambdaTest platform.

How to use CDP console in Java-TestNG automation test on LambdaTest Environment Setup Global Dependencies Install Maven Or Install Maven with Homebrew

null 11 Jul 13, 2022
A sample repo to help you set geolocation for automation test in Java-TestNG on LambdaTest. Run Selenium tests with TestNG on LambdaTest platform.

How to set geolocation for automation test in Java-TestNG on LambdaTest Environment Setup Global Dependencies Install Maven Or Install Maven with Home

null 12 Jul 13, 2022
A sample repo to help you emulate network control using CDP in Java-TestNG automation test on LambdaTest. Run Selenium tests with TestNG on LambdaTest platform.

How to emulate network control using CDP in Java-TestNG automation test on LambdaTest Environment Setup Global Dependencies Install Maven Or Install M

null 12 Oct 23, 2022
A sample repo to help you handle basic auth for automation test in Java-TestNG on LambdaTest. Run Selenium tests with TestNG on LambdaTest platform.

How to handle basic auth for automation test in Java-TestNG on LambdaTest Environment Setup Global Dependencies Install Maven Or Install Maven with Ho

null 11 Jul 13, 2022