import org.assertj.core.api.SoftAssertions;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.*;
public class AssertJ_Test {
@Test
public void 값이_같은지_검증() throws Exception {
int number = 1;
// 실제값, 기대값
assertThat(number).isEqualTo(1);
}
@Test
public void 값이_다른지_검증() throws Exception {
int number = 1;
// 실제값, 기대값
assertThat(number).isNotEqualTo(10);
}
@Test
public void null_인지_검증() throws Exception {
String isNull = null;
// 실제값, 기대값
assertThat(isNull).isNull();
}
@Test
public void null이_아닌지_검증() throws Exception {
String isNotNull = "나는존재한다";
// 실제값, 기대값
assertThat(isNotNull).isNotNull();
}
@Test
public void 값_목록에_포함되는지_검증() throws Exception {
int number = 1;
List<Integer> list = List.of(1, 2, 3, 4, 5, 6);
// 실제값, 기대값
assertThat(number).isIn(list);
}
@Test
public void 값_목록에_포함_되지_않는지_검증() throws Exception {
int number = 10;
List<Integer> list = List.of(1, 2, 3, 4, 5, 6);
// 실제값, 기대값
assertThat(number).isNotIn(list);
}
@Test
public void 값보다_작은지_검증() throws Exception {
int number = 10;
// 실제값, 기대값
assertThat(number).isLessThan(100);
}
@Test
public void 값보다_작은지_검증2() throws Exception {
int nowYear = LocalDate.now().getYear();
int afterYear = LocalDate.now().plusYears(5L).getYear();
// 실제값, 기대값
assertThat(nowYear).isLessThan(afterYear);
}
@Test
public void 값보다_작은지_검증3() throws Exception {
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = LocalDateTime.now().plusDays(15).atZone(ZoneId.systemDefault());
Date nowDate = new Date();
Date afterDate = Date.from(zonedDateTime.toInstant());
// 실제값, 기대값
assertThat(nowDate.getTime()).isLessThan(afterDate.getTime());
}
@Test
public void 값보다_작거나_같은지_검증() throws Exception {
// 실제값, 기대값
// => 10 은 20보다 작거나 같다
assertThat(10).isLessThanOrEqualTo(20);
}
@Test
public void 값보다_큰지_검증() throws Exception {
// 실제값, 기대값
// => 20 은 10 보다 크다
assertThat(20).isGreaterThan(10);
}
@Test
public void 값보다_크거나_같은지_검증() throws Exception {
// 실제값, 기대값
// => 20 은 20 보다 크거나 같다
assertThat(20).isGreaterThanOrEqualTo(20);
}
@Test
public void 값_A와_값_B_사이에_포함된다() throws Exception {
// 실제값, 기대값
// => 값 50은 1과 100사이에 포함된다
assertThat(50).isBetween(1, 100);
}
@Test
public void True_인지_검증() throws Exception {
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = LocalDateTime.now().plusDays(15).atZone(ZoneId.systemDefault());
Date nowDate = new Date();
Date afterDate = Date.from(zonedDateTime.toInstant());
// 실제값, 기대값
// nowDate 가 afterDate 보다 과거이냐?
assertThat(nowDate.before(afterDate)).isTrue();
}
@Test
public void False_인지_검증() throws Exception {
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = LocalDateTime.now().plusDays(15).atZone(ZoneId.systemDefault());
Date nowDate = new Date();
Date afterDate = Date.from(zonedDateTime.toInstant());
// 실제값, 기대값
// afterDate 가 nowDate 보다 과거이냐?
assertThat(afterDate.before(nowDate)).isFalse();
}
/**
* String
*/
@Test
public void 문자열을_다_포함_하는지_검증() throws Exception {
// 실제값, 기대값
// "피자나라치킨공주" 글자에는 "피자"와 "치킨"이라는 글자가 포함된다
assertThat("피자나라치킨공주").contains("피자", "치킨");
}
@Test
public void 해당_문자열이_딱_한번만_존재_하는지_검증() throws Exception {
// 실제값, 기대값
// "피자나라치킨공주" 글자에는 "피자" 라는 글자가 딱 한번만 포함된다
assertThat("피자나라치킨공주").containsOnlyOnce("피자");
}
@Test
public void 문자열에_오직_숫자만_있는지_검증() throws Exception {
String phone = "01012345678";
// 실제값, 기대값
// phone 이라는 문자열 변수에 오직 숫자로 이루어져 있다
assertThat(phone).containsOnlyDigits();
}
@Test
public void 문자열에_공백이_있는지_검증() throws Exception {
String text = "white space";
// 실제값, 기대값
// text 이라는 문자열 변수에 공백 문자가 포함된다
assertThat(text).containsWhitespaces();
}
@Test
public void 공백_으로만_이루어진_문자열_인지_검증() throws Exception {
String whiteSpaceText = " ";
// 실제값, 기대값
// whiteSpaceText 이라는 문자열 변수는 공백문자로만 이루어져 있다
assertThat(whiteSpaceText).containsOnlyWhitespaces();
}
@Test
public void 정규_표현식을_만족하는지_검증() throws Exception {
String phone = "01012345678";
// 실제값, 기대값
// phone 이라는 문자열 변수는 숫자로만 이루어져 있다
assertThat(phone).containsPattern("^[0-9]+$");
}
@Test
public void 문자열이_글자를_포함하지_않는지_검증() throws Exception {
String foodNames = "치킨과피자";
// 실제값, 기대값
// foodNames 이라는 문자열 변수는 "햄버거", "스파게티" 라는 글자가 없다
assertThat(foodNames).doesNotContain("햄버거", "스파게티");
}
@Test
public void 공백_문자_를_포함하지_않은지_검증() throws Exception {
String foodNames = "치킨과피자";
// 실제값, 기대값
// foodNames 이라는 문자열 변수는 공백문자가 없다
assertThat(foodNames).doesNotContainAnyWhitespaces();
}
@Test
public void 공백_문자_로만_이루어진_문자가_아닌지_검증() throws Exception {
String message = "Hello ";
// 실제값, 기대값
// message 이라는 문자열 변수는 공백문자로만 이루어져 있지 않다 (즉, 글자가 있다)
assertThat(message).doesNotContainOnlyWhitespaces();
}
@Test
public void 정규_표현식을_만족하지_않는지_검증() throws Exception {
String phone = "홍길동01012345678";
// 실제값, 기대값
// phone 이라는 문자열 변수는 숫자로만 이루어져 있지 않다
assertThat(phone).doesNotContainPattern("^[0-9]+$");
}
@Test
public void 특정_문자로_시작_하는지_검증() throws Exception {
String frameWork = "spring data jpa";
// 실제값, 기대값
// frameWork 이라는 문자열 변수는 "spring" 이라는 글자로 시작한다
assertThat(frameWork).startsWith("spring");
}
@Test
public void 특정_문자로_시작_하지_않는지_검증() throws Exception {
String application = "egov spring application";
// 실제값, 기대값
// application 이라는 문자열 변수는 "spring" 이라는 글자로 시작한다
assertThat(application).doesNotStartWith("spring");
}
@Test
public void 특정_문자로_끝나는지_하는지_검증() throws Exception {
String frameWork = "spring data jpa";
// 실제값, 기대값
// frameWork 이라는 문자열 변수는 "jpa" 이라는 글자로 끝난다
assertThat(frameWork).endsWith("jpa");
}
@Test
public void 특정_문자로_끝나지_않는지_검증() throws Exception {
String application = "egov spring application";
// 실제값, 기대값
// application 이라는 문자열 변수는 "egov" 이라는 글자로 끝나지 않는다
assertThat(application).doesNotEndWith("egov");
}
/**
* 숫자에 대한 추가 검증
*/
@Test
public void 값이_0_인지_검증() throws Exception {
int zeroCount = 0;
// 실제값, 기대값
// zeroCount 은 0 이다
assertThat(zeroCount).isZero();
}
@Test
public void 값이_0_이_아닌지_검증() throws Exception {
int count = 10;
// 실제값, 기대값
// count 은 0 이 아니다
assertThat(count).isNotZero();
}
@Test
public void 값이_0_이_양수_인지_검증() throws Exception {
int age = 132;
// 실제값, 기대값
// age 은 양수이다
assertThat(age).isPositive();
assertThat(age).isNotNegative();
}
@Test
public void 값이_0_이_음수_인지_검증() throws Exception {
int myCash = -1;
// 실제값, 기대값
// myCash 은 음수이다
assertThat(myCash).isNotPositive();
assertThat(myCash).isNegative();
}
/**
* 날짜에 대한 검증
*/
@Test
public void 비교할_값_보다_이전_날짜_인지_검증() throws Exception {
LocalDateTime nowDateTime = LocalDateTime.now();
LocalDateTime afterDateTime = LocalDateTime.of(2030, 12, 31, 23, 59, 59);
// 실제값, 기대값
// nowDateTime 은 afterDateTime 보다 이전이다
assertThat(nowDateTime).isBefore(afterDateTime);
}
@Test
public void 비교할_값_보다_이전_이거나_같은_날짜_인지_검증() throws Exception {
LocalDateTime nowDateTime = LocalDateTime.now();
LocalDateTime afterDateTime = LocalDateTime.of(
nowDateTime.getYear(),
nowDateTime.getMonthValue(),
nowDateTime.getDayOfMonth(),
nowDateTime.getHour(),
nowDateTime.getMinute(),
nowDateTime.getSecond(),
nowDateTime.getNano()
);
LocalDateTime beforeDateTime = LocalDateTime.now().minusDays(1);
// 실제값, 기대값
// nowDateTime 은 afterDateTime 보다 이전 이거나 같다
assertThat(nowDateTime).isBeforeOrEqualTo(afterDateTime);
// beforeDateTime 은 nowDateTime 보다 이전 이거나 같다
assertThat(beforeDateTime).isBeforeOrEqualTo(nowDateTime);
}
@Test
public void 비교할_값_보다_이후_날짜_인지_검증() throws Exception {
LocalDateTime nowDateTime = LocalDateTime.now();
LocalDateTime afterDateTime = LocalDateTime.now().plusDays(10);
// 실제값, 기대값
// afterDateTime 은 nowDateTime 보다 이후 이다(미래)
assertThat(afterDateTime).isAfter(nowDateTime);
}
@Test
public void 비교할_값_보다_이후_이거나_같은_날짜_인지_검증() throws Exception {
LocalDateTime nowDateTime = LocalDateTime.now();
LocalDateTime afterDateTime = LocalDateTime.now().plusYears(1);
// 실제값, 기대값
// afterDateTime 은 nowDateTime 보다 이후 이거나 같다
assertThat(afterDateTime).isAfterOrEqualTo(nowDateTime);
}
@Test
public void 날짜_의_특정_칼럼_을_제외하고_나머지_값이_같은지_검증() throws Exception {
LocalDateTime nowDateTime = LocalDateTime.now();
LocalDateTime beforeDateTime1 = LocalDateTime.now().minusNanos(1);
LocalDateTime beforeDateTime2 = LocalDateTime.now().minusSeconds(1);
LocalDateTime beforeDateTime3 = LocalDateTime.now().minusMinutes(1);
LocalDateTime beforeDateTime4 = LocalDateTime.now().minusHours(1);
// 실제값, 기대값
// nowDateTime 은 beforeDateTime1 의 나노초를 제외한 시간대는 같다
assertThat(nowDateTime).isEqualToIgnoringNanos(beforeDateTime1);
// nowDateTime 은 beforeDateTime2 의 초 이하를 제외한 시간대는 같다
assertThat(nowDateTime).isEqualToIgnoringSeconds(beforeDateTime2);
// nowDateTime 은 beforeDateTime3 의 분 이하를 제외한 시간대는 같다
assertThat(nowDateTime).isEqualToIgnoringMinutes(beforeDateTime3);
// nowDateTime 은 beforeDateTime3 의 시간 이하를 제외한 시간대는 같다
assertThat(nowDateTime).isEqualToIgnoringHours(beforeDateTime4);
}
/**
* 컬렉션에 대한 검증
*/
// List Or Set
@Test
public void 컬렉션의_크기가_기대한_값과_같은지_검증() throws Exception {
List<Integer> list = List.of(1, 2, 3, 4, 5);
// 실제값, 기대값
// list 은 크기가 5 이다
assertThat(list).hasSize(5);
}
@Test
public void 컬렉션이_해당_값을_포함_하는지_검증() throws Exception {
List<Integer> list = List.of(1, 2, 3, 4, 5);
// 실제값, 기대값
// list 은 1,2,3 을 포함한다
assertThat(list).contains(1, 2, 3);
}
@Test
public void 컬렉션이_지정한_값만_포함_하는지_검증() throws Exception {
List<Integer> list = List.of(1, 2, 3, 4);
// 실제값, 기대값
// list 은 정확히 1,2,3,4 만 가지고 있다
assertThat(list).containsOnly(1, 2, 3, 4);
}
@Test
public void 컬렉션이_지정한_값의_일부를_포함_하는지_검증() throws Exception {
List<Integer> list = List.of(1, 2, 3, 4);
// 실제값, 기대값
// list 은 1, 3, 5, 7, 9 중에 일부를 포함한다 (1, 3)
assertThat(list).containsAnyOf(1, 3, 5, 7, 9);
}
@Test
public void 컬렉션이_지정한값을_딱_한번만_포함_하는지_검증() throws Exception {
List<Integer> list = List.of(1, 2, 3, 4);
// 실제값, 기대값
// list 은 1, 3 을 딱 한번만 포함한다
assertThat(list).containsOnlyOnce(1,3);
}
// Map
@Test
public void Map이_지정한_키를_포함_하는지_검증() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("age", 132);
map.put("name", "ksj");
// 실제값, 기대값
// map 은 age 라는 키를 가지고 있다
assertThat(map).containsKey("age");
}
@Test
public void Map이_지정한_키들을_포함_하는지_검증() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("age", 132);
map.put("name", "ksj");
// 실제값, 기대값
// map 은 age, name 라는 키들을 가지고 있다
assertThat(map).containsKeys("age", "name");
}
@Test
public void Map이_지정한_키만_포함_하는지_검증() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("age", 132);
map.put("name", "ksj");
// map.put("name2", "ksj");
// 실제값, 기대값
// map 은 age, name 라는 키들만 가지고 있다
assertThat(map).containsOnlyKeys("age", "name");
}
@Test
public void Map이_지정한_키를_포함_하지_않는지_검증() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("age", 132);
map.put("name", "ksj");
// 실제값, 기대값
// map 은 title 라는 키를 갖지 않는다
assertThat(map).doesNotContainKey("title");
}
@Test
public void Map이_지정한_키들을_포함_하지_않는지_검증() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("age", 132);
map.put("name", "ksj");
// 실제값, 기대값
// map 은 title 라는 키를 갖지 않는다
assertThat(map).doesNotContainKeys("title", "content");
}
@Test
public void Map이_지정한_엔트리_포함_하는지_검증() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("age", 132);
map.put("name", "ksj");
Map.Entry<String, Integer> entry = Map.entry("age", 132);
// 실제값, 기대값
// map 은 Map.entry("age", 132) 라는 엔트리를 갖는지 검증
assertThat(map).contains(entry);
}
@Test
public void Map이_지정한_엔트리_포함_하는지_검증2() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("age", 132);
map.put("name", "ksj");
// 실제값, 기대값
// map 은 키는 "age" 이고 값은 132 인 엔트리를 갖는지 검증
assertThat(map).containsEntry("age", 132);
}
/**
* 익셉션 관련 검증
*/
@Test
public void 익셉션이_발생_하는지_검증() throws Exception {
assertThatThrownBy(() -> {
throw new IllegalArgumentException();
});
}
@Test
public void 해당_타입의_익셉션이_발생_하는지_검증() throws Exception {
assertThatThrownBy(() -> {
throw new IllegalArgumentException();
}).isInstanceOf(RuntimeException.class);
}
@Test
public void 해당_타입의_익셉션이_발생_하는지_검증_두번째_방법() throws Exception {
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> {
throw new IllegalArgumentException();
});
}
@Test
public void IOException_익셉션이_발생_하는지_검증() throws Exception {
assertThatIOException().isThrownBy(() -> {
throw new IOException();
});
}
@Test
public void 익셉션이_발생_하지_않는지_검증() throws Exception {
assertThatCode(() -> {
// code...
System.out.println("예외가 발생하지 않습니다");
}).doesNotThrowAnyException();
}
@Test
public void 여러_검증을_모아서_검증하기() throws Exception {
// 테스트가 실패해야 정상, 실패했을때 나오는 콘솔을 확인
SoftAssertions soft = new SoftAssertions();
soft.assertThat(1).isEqualTo(1);
soft.assertThat(10).isGreaterThan(20); // <- 거짓
soft.assertThat(10).isGreaterThan(30); // <- 거짓
soft.assertThat("1234567890").containsOnlyDigits();
soft.assertAll();
}
@Test
public void 여러_검증을_모아서_검증하기_두번째_방법() throws Exception {
// 테스트가 실패해야 정상, 실패했을때 나오는 콘솔을 확인
SoftAssertions.assertSoftly((soft) -> {
soft.assertThat(1).isEqualTo(1);
soft.assertThat(10).isGreaterThan(20); // <- 거짓
soft.assertThat(10).isGreaterThan(30); // <- 거짓
soft.assertThat("1234567890").containsOnlyDigits();
});
}
/**
* 테스트 설명달기
*/
@Test
public void 테스트에_설명_달기_1() throws Exception {
// 실패해야 정상
assertThat(1)
.as("1은 양의 정수이다")
.isNegative();
}
@Test
public void 테스트에_설명_달기_2() throws Exception {
String message = "1은 양의 정수이다";
// 실패해야 정상
assertThat(1)
.as("[정수 검사] %s", message)
.isNegative();
}
@Test
public void 테스트에_설명_달기_3() throws Exception {
// 실패해야 정상
assertThat(1)
.describedAs("1은 양의 정수이다")
.isNegative();
}
@Test
public void 테스트에_설명_달기_4() throws Exception {
// 실패해야 정상
String message = "1은 양의 정수이다";
// 실패해야 정상
assertThat(1)
.describedAs("[정수 검사] %s", message)
.isNegative();
}
}