Dev 달팽이 @_''

Java - JUnit 5 테스트 반복 본문

Java&Spring/더 자바, 어플리케이션을 테스트하는 다양한 방법

Java - JUnit 5 테스트 반복

다본죽 2022. 1. 11. 22:58

Java - JUnit 5 테스트 반복

 

@RepeatedTest

  • 반복 횟수와 반복 테스트 이름을 설정할 수 있다.
    • {displayName}
    • {currentRepetition}
    • {totalRepetitions}
  • RepetitionInfo 타입의 인자를 받을 수 있다.
@DisplayName("스터디 만들기")
@RepeatedTest(value = 10, name = "{displayName} {currentRepetition}/{totalRepetitions}")
void repeatTest(RepetitionInfo repetitionInfo){
	System.out.println("test" + repetitionInfo.getCurrentRepetition()+"/"+repetitionInfo.getTotalRepetitions());
}

 

@ParameterizedTest

  • 테스트에 여러 다른 매개변수를 대입해가며 반복 실행한다.
    • {displayName}
    • {index}
    • {arguments}
    • {0},{1},...
@DisplayName("스터디 만들기")
@ParameterizedTest(name = "{index} {displayName} message={0}")
@ValueSource(strings = {"날씨가", "많이", "추워지고", "있네요."})
void parameterizedTest(String message){
	System.out.println(message);
}

 

인자 값들의 소스

  • @ValueSource
  • @NullSource, @EmptySource, @NullAndEmptySource
  • @EnumSource
  • @MethodSource
  • @CsvSource
  • @CsvFileSource
  • @ArgumentSource

인자 값 타입 변환

    @DisplayName("스터디 만들기")
    @ParameterizedTest(name = "{index} {displayName} message={0}")
    @ValueSource(ints = {10,20,40})
    void parameterizedTest3(@ConvertWith(StudyConverter.class) Study study){
        System.out.println(study.getLimit());
    }

    static class StudyConverter extends SimpleArgumentConverter{

        @Override
        protected Object convert(Object source, Class<?> targetType) throws ArgumentConversionException {
            assertEquals(Study.class, targetType, "Can only convert to Study");
            return new Study(Integer.parseInt(source.toString()));
        }
    }

  • SimpleArgumentConverter를 상속받은 클래스를 확인하여 타입 변환
  • @ConvertWith을 통하여 클래스를 확인

인자값 조합

  • ArgumentsAccessor
  • 커스텀 Accessor
    • ArgumentsAggregator 인터페이스 구현
    • @AggregateWith
    @DisplayName("스터디 만들기")
    @ParameterizedTest(name = "{index} {displayName} message={0}")
    @CsvSource({"10, '자바 스터디'","20, 스프링"})
    void parameterizedTest4(@AggregateWith(StudyAggregator.class) Study study){
        System.out.println(study);
    }

    // 반드시 public class 형태로 만들어줘야하거나, inner static class여야 함
    static class StudyAggregator implements ArgumentsAggregator{
        @Override
        public Object aggregateArguments(ArgumentsAccessor argumentsAccessor, ParameterContext parameterContext) throws ArgumentsAggregationException {
            return new Study(argumentsAccessor.getInteger(0),argumentsAccessor.getString(1));
        }
    }

  • ArgumentsAggregator 인터페이스를 구현한 클래스를 확인하여 타입 변환
  • 클래스는 반드시 public class 형태로 만들어주거나
  • inner static class 이어야 함

 

'Java&Spring > 더 자바, 어플리케이션을 테스트하는 다양한 방법' 카테고리의 다른 글

Java - Mockito  (0) 2022.01.13
Java - JUnit 5  (0) 2022.01.11