본문 바로가기
카테고리 없음

[TDD] @ParameterizedTest 사용하기

by cook_code 2023. 3. 29.
반응형

@ParameterizedTest

  • 한 개의 메소드에 대해 여러 개의 테스트를 수행해야 하는 경우에 사용하는 어노테이션 
  • @Test 대신 @ParameterizedTest 로 적는다. 
  • arguments를 활용해 테스트를 여러 번 수행할 수 있다. 

사칙 연산 계산기 테스트 코드 작성 예시 

1. 의존성 추가 

    testImplementation 'org.junit.jupiter:junit-jupiter-params:5.8.2'

2. ENUM 클래스 작성 

package org.example;

import java.util.Arrays;

public enum ArithmeticOperator {
    ADDITION("+") {
        @Override
        public int arithmeticCalculate(int operand1, int operand2) {
            return operand1 + operand2;
        }
    }, SUBTACTION("-") {
        @Override
        public int arithmeticCalculate(int operand1, int operand2) {
            return operand1 - operand2;
        }
    }, MULTIPLICATION("*") {
        @Override
        public int arithmeticCalculate(int operand1, int operand2) {
            return operand1 * operand2;
        }
    }, DIVISION("/") {
        @Override
        public int arithmeticCalculate(int operand1, int operand2) {
            return operand1 / operand2;
        }
    };
    private final String operator;

    ArithmeticOperator(String operator) {
        this.operator = operator;
    }

    //arthmeticCalculate 추상메서드는 연산 각각에 오버라이딩되어 활용
    public abstract int arithmeticCalculate(final int operan1, final int operand2);

    //
    public static int calculate(int operand1, String operator, int operand2) {
        ArithmeticOperator arithmeticOperator = Arrays.stream(values())
                .filter(v->v.operator.equals(operator))
                .findFirst()
                .orElseThrow(()->new IllegalArgumentException("올바른 사칙연산이 아닙니다."));
        return arithmeticOperator.arithmeticCalculate(operand1, operand2);
    }

}

3. 테스트 코드 

package org.example;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.stream.Stream;

import static org.assertj.core.api.Assertions.*;
import static org.junit.jupiter.params.provider.Arguments.arguments;

/*
* 사칙연산 계산기 구현
• 요구사항
• 간단한 사칙연산을 할 수 있다.
• 양수로만 계산할 수 있다.
• 나눗셈에서 0을 나누는 경우 IllegalArgument 예외를 발생시킨다.
• MVC패턴(Model-View-Controller) 기반으로 구현한다.
* */


public class CalculatorTest {

    @DisplayName("사칙 연산을 수행한다.")
    @ParameterizedTest
    @MethodSource("formulaAndResult")
    void calculateTest(int operand1, String operator, int operand2, int result) {
    
        int calculateResult = Calculator.calculate(operand1, operator, operand2);

        assertThat((calculateResult)).isEqualTo(result);
    }

    private static Stream<Arguments> formulaAndResult() {
        return Stream.of(
                arguments(1, "+", 2, 3),
                arguments(1, "-", 2, -1),
                arguments(4, "*", 2, 8),
                arguments(4, "/", 2, 2)
        );
    }
}

4. 구현부 

package org.example;

public class Calculator {

    public static int calculate(int operand1, String operator, int operand2) {
    	return ArithmeticOperator.calculate(operand1, operator, operand2);
    }
}

5. 수행 결과 

추가 학습

  • Stream 작업 순서 

스트림 변환 -> 필터 -> 매핑 -> 정렬 -> 반환

  • Stream filter

- 스트림 내 요소에 대해 필터링하는 작업 

- findFirst() : 조건에 맞는 첫번째 요소를 가져온다. (전부를 가져오고 싶다면 작성하지 않아도 됨)

- orElseThrow() : 조건에 맞지 않는다면 ("메시지") 출력

  • Stream.of

Stream.of 메소드를 사용하면 스트림 객체를 바로 생성할 수 있다. 

  • MethodSource()

- 테스트 메소드 호출 당 하나의 인수를 전달하는 경우에는 <Arguments> 추상화를 사용하지 않아도 된다. 

- MethodSource()에 사용하는 이름은 존재하는 메소드와 같은 이름이어야 한다. 

- 클래스 단위 생명 주기가 아닌 경우, static으로 선언해야 한다. 

참고 블로그

 

 

[JUnit] JUnit5 사용법 - Parameterized Tests - Heee's Development Blog

Step by step goes a long way.

gmlwjd9405.github.io

 

java stream 정리(filter)

Repository = java-practice

isntyet.github.io

 

반응형