아래와 같이 반복적인 테스트 코드를 작성해야 할 때가 있다.
@Test
public void testFree() throws Exception {
//given
Event event = Event.builder()
.basePrice(0)
.maxPrice(0)
.build();
//when
event.update();
//then
assertThat(event.isFree()).isTrue();
//given
event = Event.builder()
.basePrice(100)
.maxPrice(0)
.build();
//when
event.update();
//then
assertThat(event.isFree()).isFalse();
//given
event = Event.builder()
.basePrice(0)
.maxPrice(100)
.build();
//when
event.update();
//then
assertThat(event.isFree()).isFalse();
}
그럴때 parameter를 사용하자 maven repository에서 JUnitParams 라이브러리를 가져와 설정파일에 넣어주면
test code에서 사용할 수 있다.
test class에 @RunWith를 설정해주고 JUnitParamsRunner.class 를 주입시킨다.
(JUnit5 에서는 RunWith 대신 ExtendWith 사용)
그럼 아래처럼 파라미터를 넣어 반복되는 코드를 생략 할 수 있다.
@Test
@Parameters({
"0, 0, true",
"100, 0, false",
"0, 100, false"
})
public void testFree(int basePrice, int maxPrice, boolean isFree) throws Exception {
//given
Event event = Event.builder()
.basePrice(basePrice)
.maxPrice(maxPrice)
.build();
//when
event.update();
//then
assertThat(event.isFree()).isEqualTo(isFree);
저 @Parameters 에 파라미터들이 문자열이라 신경 쓰인다면??
객체로 만들어서 넣어주자!
@Test
@Parameters(method = "parametersForTestFree") // method 생략 가능
public void testFree(int basePrice, int maxPrice, boolean isFree) throws Exception {
...
private Object[] parametersForTestFree(){
return new Object[]{
new Object[] {0, 0, true},
new Object[] {100, 0, false},
new Object[] {0, 100, false},
new Object[] {100, 200, false}
};
}
위처럼 작성해 줄 때 method 이름은 생략이 가능하다.
→ parametersFor란 prefix 뒤에 붙어있는 테스트 메소드 이름을 찾아서 자동으로 파라미터로 사용 해준다.
'JAVA' 카테고리의 다른 글
spring hateoas (0) | 2022.08.01 |
---|---|
spring restdocs 참고 (0) | 2022.07.28 |
error serializer (0) | 2022.07.11 |
testcode 작성 시 description (0) | 2022.07.11 |
spring boot build 와 실행 (0) | 2022.07.06 |