본문으로 건너뛰기
버전: 10.x

@FreezeBy 애너테이션

@FreezeBy 애너테이션을 사용하면 테스트에서 값 동결을 세밀하게 제어할 수 있습니다. 단일 값을 동결하고 유형이나 이름과 같은 특정 조건과 일치하는 여러 생성 대상에서 이를 재사용할 수 있습니다. 이는 테스트 가독성을 향상시키고 생성된 값들 간의 일관성을 보장하는 데 도움이 됩니다.

Matching Strategies

AutoParams는 객체 생성 중에 동결된 값을 받아야 하는 대상을 결정하는 여러 가지 매칭 전략을 제공합니다. 다음 예에서 몇 가지 전략을 보여줍니다.

  • EXACT_TYPE

    정확히 동일한 유형을 가진 모든 대상에 대해 동결된 값을 재사용합니다.

    @AllArgsConstructor
    @Getter
    public class StringContainer {

    private final String value;
    }
    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());
    }
    }

    이 예에서 StringContainer 내부의 String 필드를 포함한 모든 String 대상은 동일한 동결된 값으로 생성됩니다.

  • IMPLEMENTED_INTERFACES

    동결된 값이 인터페이스를 구현하고 있다면, 해당 인터페이스 타입의 대상에도 같은 값을 재사용합니다.

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

    이 예에서 StringCharSequence를 구현하므로 동결된 값 s1chars에 재사용됩니다. StringContainer는 해당 유형이 인터페이스가 아니므로 영향을 받지 않습니다.

  • PARAMETER_NAME

    일치하는 이름을 가진 다른 대상에 대해 고정된 값을 재사용합니다.

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

    이 전략은 이름이 역할을 반영하는 일관된 규칙을 따르는 경우에 유용합니다.


    노트

    이 기능은 런타임에 매개변수 이름의 사용 가능 여부에 따라 달라집니다. 자세한 내용은 도메인 특화 언어(DSL)를 사용한 일회성 사용자 정의 섹션의 노트를 참조하세요.

여러 매칭 전략을 결합하여 동결 범위를 넓힐 수도 있습니다.

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

이 예에서는 고정된 값 s1s2(동일한 유형)와 chars(String으로 구현된 인터페이스) 모두에 재사용됩니다.

Shorthand for EXACT_TYPE

@Freeze를 사용하는 것은 @FreezeBy(EXACT_TYPE)와 같습니다. 이는 가장 일반적인 매칭 전략을 간편하게 단축하는 방법입니다.

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