AssertThat란?
Java에서 주로 테스트 프레임워크(예: JUnit 또는 Hamcrest)를 사용할 때 등장하는 단언 메서드다.
테스트의 가독성을 높이고 직관적인 단언을 지원하는 데 사용된다.
assertThat의 주요 특징
- Hamcrest와의 통합
- assertThat은 JUnit의 일부로 제공되지만, Hamcrest 라이브러리와 함께 사용된다.
- Hamcrest의 매처(Matchers)를 활용하여 단언 조건을 정의할 수 있다.
- 가독성 향상
- 예를 들어, assertThat(value, is(expectedValue))는 "값이 기대값인지 확인한다"는 의도가 명확히 드러난다.
- 다양한 매처 지원
- Hamcrest는 숫자, 문자열, 컬렉션 등 다양한 데이터 타입에 대해 매처를 제공한다.
- 예 ) is(), equalTo(), containsString(), hasItems(), greaterThan(), lessThan() 등.
사용하는 이유
- 가독성: 테스트 조건이 명확하게 드러나므로, 다른 개발자도 테스트 코드를 쉽게 이해할 수 있습니다.
- 확장성: Hamcrest의 매처를 사용하거나 커스텀 매처를 정의하여 복잡한 테스트 조건도 간결하게 표현할 수 있습니다.
- 표준화: JUnit과 Hamcrest는 널리 사용되는 표준 도구로, 테스트 코드 작성에 일관성을 제공합니다.
기본 문법
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
assertThat(actualValue, matcher);
- actulValue : 실제 값
- matcher : 기대 조건을 정의하는 Hamcrest 매처
예제 코드
전체적인 메서드 사용 코드
| 메서드 | 설명 |
| isTrue(boolean condition, String message) | 조건이 true인지 확인. false이면 예외 발생. |
| state(boolean condition, String message) | 상태가 유효한지 확인.false이면 예외 발생. |
| notNull(Object object, String message) | 객체가 null이 아닌지 확인. |
| isNull(Object object, String message) | 객체가 null이 아닌지 확인. |
| isInstanceOf(Class<?> clazz, Object obj, String message) | 객체가 특정 클래스의 인스턴스인지 확인. |
| isAssignable(Class<?> superType,Class<?> subType, String message) | 클래스가 특정 상위 클래스에 할당 가능한지 확인. |
| hasLength(String text, String message) | 문자열이 null이 아니고 길이가 0보다 큰지 확인. |
| hasText(String text, String message) | 문자열이 공백이 아닌 텍스트를 포함하는지 확인. |
| doesNotContain(String textToSearch, String substring, String message) | 문자열에 특정 서브스트링이 포함되어 있지 않은지 확인. |
| notEmpty(Collection<?> collection, String message) | 컬렉션이 null이거나 비어있지 않은지 확인. |
| notEmpty(Map<?, ?> map, String message) | 맵이 null이거나 비어 있지 않은지 확인. |
| notEmpty(Object[] array, String message) | 배열이 null이거나 비어있지 않은지 확인. |
| noNullElements(Object[] array, String message) | 배열에 null 요소가 없는지 확인. |
import org.springframework.util.Assert;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
public class AssertExample {
public static void main(String[] args) {
// Logical assertions
try {
// 조건이 true인지 확인 (false면 IllegalArgumentException 발생)
Assert.isTrue(1 == 1, "Condition is not true");
} catch (IllegalArgumentException e) {
System.out.println("isTrue failed: " + e.getMessage());
}
try {
// 상태가 유효한지 확인 (false면 IllegalStateException 발생)
Assert.state(1 == 1, "State is not valid");
} catch (IllegalStateException e) {
System.out.println("state failed: " + e.getMessage());
}
// Object and type assertions
String hello = "world";
// 객체가 null이 아닌지 확인
Assert.notNull(hello, "Object must not be null");
// 객체가 null인지 확인
Assert.isNull(null, "Object must be null");
// 객체가 특정 클래스의 인스턴스인지 확인
String text = "text";
Assert.isInstanceOf(String.class, text, "Object must be instance of String");
// 클래스가 특정 클래스에 할당 가능한지 확인
Assert.isAssignable(AbstractMap.class, HashMap.class, "HashMap is not assignable to AbstractMap");
// Text assertions
String noBlank = " ";
// 문자열이 null이 아니고 길이가 0보다 큰지 확인
Assert.hasLength(noBlank, "String must have length");
String hasText = "abc";
// 문자열이 null이 아니고 공백이 아닌 텍스트를 포함하는지 확인
Assert.hasText(hasText, "String must have text");
// 문자열이 특정 텍스트를 포함하지 않는지 확인
String abc = "abc";
Assert.doesNotContain(abc, "z", "String contains forbidden text");
// Collection and map assertions
Collection<Integer> list = List.of(1);
// 컬렉션이 비어 있지 않은지 확인
Assert.notEmpty(list, "Collection must not be empty");
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("hello", "world");
// 맵이 비어 있지 않은지 확인
Assert.notEmpty(hashMap, "Map must not be empty");
// Array assertions
Integer[] numbers = new Integer[1];
numbers[0] = 1;
// 배열이 비어 있지 않은지 확인
Assert.notEmpty(numbers, "Array must not be empty");
// 배열에 null 요소가 없는지 확인
Assert.noNullElements(numbers, "Array must not contain null elements");
System.out.println("All assertions passed successfully.");
}
}
더보기
1. 숫자 값 비교
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class Example {
public static void main(String[] args) {
int actual = 5;
assertThat(actual, is(5)); // 값이 5인지 확인
assertThat(actual, greaterThan(3)); // 값이 3보다 큰지 확인
assertThat(actual, lessThanOrEqualTo(5)); // 값이 5 이하인지 확인
}
}
2. 문자열 비교
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class Example {
public static void main(String[] args) {
String actual = "Hello, World!";
assertThat(actual, containsString("World")); // 문자열에 "World"가 포함되어 있는지 확인
assertThat(actual, startsWith("Hello")); // "Hello"로 시작하는지 확인
assertThat(actual, endsWith("!")); // "!"로 끝나는지 확인
}
}
3. 컬렉션 테스트
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.Arrays;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<String> actual = Arrays.asList("Apple", "Banana", "Cherry");
assertThat(actual, hasItem("Banana")); // 리스트에 "Banana"가 포함되어 있는지 확인
assertThat(actual, hasItems("Apple", "Cherry")); // 리스트에 "Apple"과 "Cherry"가 포함되어 있는지 확인
assertThat(actual, contains("Apple", "Banana", "Cherry")); // 정확한 순서로 포함 여부 확인
}
}
4. 객체 속성 테스트 (Hamcrest hasProperty 사용)
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class Example {
public static void main(String[] args) {
Person person = new Person("John", 30);
assertThat(person, hasProperty("name", is("John"))); // name 속성이 "John"인지 확인
assertThat(person, hasProperty("age", greaterThan(20))); // age가 20보다 큰지 확인
}
}
※ assert에 대한 설명
'BackEnd > Java' 카테고리의 다른 글
| [JAVA] 오버라이딩(overriding) (0) | 2025.01.16 |
|---|---|
| [JAVA] 상속(inheritance) (0) | 2025.01.15 |
| [JAVA] Assert (0) | 2025.01.07 |
| JAVA 입문 (생성자) (0) | 2024.12.19 |
| JAVA 입문 (클래스) (1) | 2024.12.19 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- programmers
- db
- 생활코딩
- Kotlin
- Spring Security
- 백준
- Spring
- brute-force
- Annotation
- Java
- Algorithm
- Spring Boot
- Effective Java
- 디자인패턴
- Security
- Greedy
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함