여러 개의 테스트 케이스를 모아놓은 집합으로 소프트웨어가 정상적으로 작동하는지 확인하는 데 사용
소프트웨어 변경 후 기존 기능이 여전히 정상적으로 작동하는지 확인하는 과정
자바 프로그래밍 언어를 위한 단위 테스트 프레임워크
메소드 | 설명 |
---|---|
assertEquals(expected, actual) | 두 값이 같은지 확인 |
assertTrue(condition) | 조건이 참인지 확인 |
assertFalse(condition) | 조건이 거짓인지 확인 |
assertNull(object) | 객체가 null인지 확인 |
assertNotNull(object) | 객체가 null이 아닌지 확인 |
assertSame(expected, actual) | 두 객체가 같은 객체인지 확인 |
assertNotSame(expected, actual) | 두 객체가 다른 객체인지 확인 |
x.equals(y)
메서드가 있다.String
및 몇몇 다른 자바 클래스에 대해 잘 작동한다.equals
메서드를 정의해야 한다.
public boolean equals(Object obj) { ... }
public boolean equals(Object something) {
Person p = (Person)something;
return this.name == p.name; // 원하는 대로 비교할 수 있다.
}
/** IMath 클래스를 테스트하는 클래스이다. */
public class IMathTestNoJUnit {
/** 테스트를 실행한다. */
public static void main(String[] args) {
printTestResult(0);
printTestResult(1);
printTestResult(2);
printTestResult(3);
printTestResult(4);
printTestResult(7);
printTestResult(9);
printTestResult(100);
}
private static void printTestResult(int arg) {
System.out.print("isqrt(" + arg + ") ==> ");
System.out.println(IMath.isqrt(arg));
}
}
// 실행 결과
// isqrt(0) ==> 0
// isqrt(1) ==> 1
// isqrt(2) ==> 2
// isqrt(3) ==> 2
// isqrt(4) ==> 2
// isqrt(7) ==> 3
// isqrt(9) ==> 3
// isqrt(100) ==> 10
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class IMathTest extends TestCase{
@Test
public void testIsqrt() {
assertEquals(0, IMath.isqrt(0));
assertEquals(1, IMath.isqrt(1));
assertEquals(2, IMath.isqrt(2));
assertEquals(2, IMath.isqrt(3));
assertEquals(2, IMath.isqrt(4));
assertEquals(3, IMath.isqrt(7));
assertEquals(3, IMath.isqrt(9));
assertEquals(10, IMath.isqrt(100));
}
}
// 실행 결과
// 테스트 케이스가 성공하면 아무것도 출력되지 않음
// 테스트 케이스가 실패하면 다음과 같이 출력됨
// java.lang.AssertionError: expected:<0> but was:<1>
public class ForYou {
public static int min(int x, int y){
if(x < y) return x;
else return y;
}
}
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ForYouTest extends TestCase{
@Test
public void testMin() {
assertEquals(1, ForYou.min(1, 2));
assertEquals(1, ForYou.min(2, 1));
assertEquals(0, ForYou.min(0, 0));
assertEquals(-1, ForYou.min(-1, 0));
assertEquals(-1, ForYou.min(0, -1));
}
}
테스트 케이스 전 또는 후에 실행하고자 하는 코드
protected void setUp() { ... }
protected void tearDown() { ... }
protected void runTest() {
setUp();
// <run the test>;
tearDown();
}
AssertionFailedError
를 던진다.