naver / fixture-monkey

Let Fixture Monkey generate test instances including edge cases automatically
https://naver.github.io/fixture-monkey
Apache License 2.0
554 stars 85 forks source link

Is there a way to set only positive numbers in a numeric field? #1011

Closed eastglow closed 1 month ago

eastglow commented 1 month ago

안녕하세요. Fixture Monkey를 잘 사용하고 있는 중에 궁금한 점이 있어 질문드립니다.


1)

int, double, bigDecimal 등 숫자형 값이 들어오는 필드들에 대해 일괄적으로 0 혹은 0보다 큰 랜덤한 양수만 세팅되도록 범위를 지정할 수 있는 방법이 있는지 궁금합니다. (@Min 같은 field annotation을 사용하지 않고)

builder를 생성할 때 generator 설정을 통해 해결할 수 있을 것 같긴 한데 아직 방법을 찾지 못했네요 ㅠ


2)

특정 값들의 그룹 안에서 랜덤한 값이 선택되게 하려면 아래처럼 사용하는 것이 일반적일까요? 이렇게 특정 그룹 내 랜덤한 값을 선택하게 하려할 때 null도 포함해서 할 수 있을까요? A,B,C 그리고 null 4가지 중 한가지가 세팅되도록 하려는 목적입니다.

FixtureMonkey fixtureMonkey = FixtureMonkey.builder()
        .defaultNotNull(true)
        .register(
                TestDto.class,
                fixture -> fixture.giveMeBuilder(TestDto.class)
                        .set(javaGetter(TestDto::getTestField), Arbitraries.of("A", "B", "C").sample())
        )
        .build();
flex-myeonghyeon commented 1 month ago

@eastglow 안녕하세요 아래와 같이 가이드 드립니다

1) 특정 타입의 기본 생성 값 범위 지정 방법

위의 두가지 설정은 아래 SimpleValueJqwikPlugin 에서 기본 값 설정하는 코드를 참고하시면 이해하시고 필요한 정의를 구현해서 넣으실 수 있으실거라 생각됩니다 https://github.com/naver/fixture-monkey/blob/2fcfc5107a52da34a40793189bee122e75b89cbc/fixture-monkey-api/src/main/java/com/navercorp/fixturemonkey/api/plugin/SimpleValueJqwikPlugin.java#L137-L169

추가로 더 단순하게 하고 싶으시면 SimpleValueJqwikPlugin 를 사용하면서 여기의 몇가지 제공되는 옵션을 설정하셔도 될거 같습니다 아래의 옵션들을 참고하셔서 SimpleValueJqwikPlugin 에 설정 변경하시면 쉽게 적용될것입니다 https://github.com/naver/fixture-monkey/blob/2fcfc5107a52da34a40793189bee122e75b89cbc/fixture-monkey-api/src/main/java/com/navercorp/fixturemonkey/api/plugin/SimpleValueJqwikPlugin.java#L70-L80

2) 특정 값 정의 설정시 null 포함 Arbitraries.of("A", "B", "C").injectNull(0.2) 이렇게 하면 sample 시 20% 확률로 null 이 생성됩니다 (1.0 이 100%)

추가로 아래 설정에서 의견을 더 드려봅니다 아래 처럼 .set 에 sample() 된 값을 설정하면 "A", "B", "C" 중 하나 값이 생성되고 TestDto 의 testField 에는 항상 이 값으로만 생성되게 됩니다 혹시 이게 의도였다면 상관없지만 TestDto 생성시 마다 testField 가 "A", "B", "C" 중 하나가 매번 다른값으로 생성되길 원하신다면 sample 호출은 빼고 Arbitrary 만 set 해주면 매번 생성시마다 sample 을 호출해 다른 값을 생성하게 합니다

.register(
    TestDto.class,
    fixture -> fixture.giveMeBuilder(TestDto.class)
        .set(javaGetter(TestDto::getTestField), Arbitraries.of("A", "B", "C").sample())
)

종합하면 아래와 같이 설정하시면 될거 같습니다

.register(
    TestDto.class,
    fixture -> fixture.giveMeBuilder(TestDto.class)
        .set(javaGetter(TestDto::getTestField), Arbitraries.of("A", "B", "C").injectNull(0.2))
)
eastglow commented 1 month ago

@flex-myeonghyeon

상세한 가이드 감사드립니다. 2번의 경우는 말씀하신 것처럼 A,B,C 중 하나가 매번 다른 값으로 생성되는걸 의도한게 맞고 말씀하신 것처럼 sample을 제외하고 호출하는 것으로 수정하였습니다.

1번은 SimpleValueJqwikPlugin 코드 참고하여 한번 세팅해보도록 하겠습니다.