Java Unit testing with JUnit 4.x in Eclipse - Tutorial
꺼리/공부 2008. 7. 9. 08:11저자 : Lars Vogel < webmaster@vegella.de >
Version 0.2
Copyright 2007 Lars Vogel
30. 06. 2007
오역 및 수정 : Hans Baek < hans.baek@gmail.com >
Korean Version 0.1 (Ganymede로 Test)
Copydown 2008 Hans Baek
08. 07. 2007
Abstract
이 문서는 JUnit 4.x의 간단한 개요와 이클립스를 이용한 그 사용법에 대한 것이다. JUnit4의 새로운 주석을 사용하여 테스트를 생성하는 것과 JUnit4 test suit의 생성에 대하여 설명한다. 여러분은 이 문서를 읽은 후에 이클립스로부터 JUnit을 사용하여 test를 실행 할 수 있을 것이다.
-
General
-
Unit Testing
단위 테스트란 개발자에 의해 쓰여진 작은 코드로써 그 코드는 매우 작고, 테스트 되어야 하는 코드의 특정 영역을 검사한다. 이것은 코딩 혹은 프로그램이 실행되고 있는 환경의 의 변경 후에 기존의 기능이 잘 동작하는지를 확인하는데 사용될 수 있다.
JUnit 4.는 Erich Gamma와 Kent Beck에 의해 작성된 자동으로 java code를 시험하기 위한 프레임워크이다. JUnit은 test method들을 인식하기 위해 annotation(주석)을 사용한다.
JUnit의 매우 중요한 가정은 모든 시험은 임의의 순서대로 수행될 수 있다는 것이다. 따라서 각 시험은 고립(stand alone)되어 있어야만 하고 다른 시험에 의존되지 않는다.
- Installation
JUnit4.x를 JUnit website로 부터 다운로드 하고 classpath를 추가한다.
팁) 여러분은 Junit을 이클립스와 독립적으로 사용할 수 있다. 하지만 이클립스를 이용하여 JUnit를 사용하는 것이 와 같이 JUnit과 매우 잘 통합되어 있기 때문에 더 쉽다.
-
-
Introduction in Writing a Test
-
Overview
JUnit은 test되어야 하는 메소드를 인식하기 위해 annotations를 사용한다.
Test를 쓰기 위해서는
-
- @org.JUnit.Test annotation method를 사용한다.
- 두 값의 동등 비교를 검사하기 원할 때, import org.JUnit.Assert.* (statically) 를 사용한다. assertEqulas()를 호출하고 두 값을 전달한다.
Static import는 Java 5.0이후 버전에서 사용가능하다. (예: import static org.junit.Assert.*; )
-
Write your first test
아래와 같이 java code를 작성한다.
package testingTest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MyFirstJUnitTest {
@Test
public void simpleAdd() {
int result = 1;
int expect = 1;
assertEquals(result, expect);
}
}
-
Run your first test (Eclipse)
만일 여러분이 이클립스를 하용한다면 새로운 파일을 선택하고 마우스 오른쪽 버튼을 눌러 Run as > JUnit test를 누른다
이클립스는 JUnit 탭에서 green 혹은 red bar로 그 결과를 표시해 준다.
-
Run your first test (command line)
커맨드 라인을 열고 다음가 같은 명령어를 입력한다.
org.junit.JUnitCore.runClasses(TestClass1.class, …);
-
JUnit with Eclipse
-
Preparation
새로운 프로젝트를 생성한다. 이 프로젝트에 lib folder를 추가한다. Junit.jar를 이 폴어데 복사한다. 이클립스의 build path에 추가한다.
새로운 source folder "junit"을 프로젝트에 생성한다. 프로젝트를 선택하고 마우스 오른쪽 버튼을 누른다. Properties를 선택한다. Java build path를 선택하고 Source Code 탭을 선택한다.
Add folder 버튼을 누른 후 Create new folder를 누른다. "junit" 폴더를 생성한다.
-
Create a normal class
"MyClass" class를 생성한다. 이 Class를 test할 때 사용할 것이다.
-
public class MyClass {
public int multiply (int x, int y) {
return x / y;
}
}
-
Create a test class
JUnit.jar를 build path에 추가합니다.
작성한 클래스를 선택하고 마우스 오른쪽 버튼을 눌러 New > JUnit Test Case를 선택합니다. source folder를 junit으로 변경합니다.
Next 버튼을 누르고 test하기 원하는 method를 선택합니다.
아래와 같이 test code를 작성합니다.
import static org.junit.Assert.*;
import org.junit.Test;
public class MyClassTest {
@Test
public void testMultiply() {
MyClass tester = new MyClass();
assertEquals("Result", 50, tester.multiply(10, 5));
}
}
새로운 test class를 선택하고 마우스 오른쪽 버튼을 눌러 Run As > Junit Test를 실행 합니다.
결과는 위와 같습니다. 이것은 우리의 multiplier 클래스가 현재 나누기를 하고 있기 때문입니다. 버그를 수정하고 다시 test를 수행하여 green bar가 됨을 확인 하십시오,
-
Create a test suite
만일 여러분이 여러 개의 test들을 가지고 있다면, 여러분은 그것들을 test suit로 묶을 수 있습니다.
여러분의 test class들을 선택하고 마우스 오른쪽 클릭 New > Other > Java > JUnit > JUnit Test Suit를 선택합니다.
Next 버튼을 선택하고 여러분이 생성되기 원하는 test의 메소드를 선택합니다.
Finish를 누릅니다.
-
JUnit (more) in Detail
-
Annotations
아래에 JUnit 4.x에서 사용가능한 annotation을 요약합니다.
Table 1. Annotations
-
Annotation |
Description |
@Test public void method() |
Annotation @Test identifies that this method is a test method. |
@Before public void method() |
Will perform the method() before each test. This method can prepare the test environment, e.g. read input data, initialize the class) |
@After public void method() |
Test method must start with test |
@BeforeClass public void method() |
Will perform the method before the start of all tests. This can be used to perform time intensive activities for example be used to connect to a database |
@AfterClass public void method() |
Will perform the method after all tests have finished. This can be used to perform clean-up activities for example be used to disconnect to a database |
@Ignore |
Will ignore the test method, e.g. useful if the underlying code has been changed and the test has not yet been adapted. |
@Test(expected=IllegalArgumentException.class) |
Tests if the method throws the named exception |
@Test(timeout=100) |
Fails if the method takes longer then 100 milliseconds |
-
Test statements
아래에 사용가능한 test method를 요약합니다.
Table 2. Test methods
Statement |
Description |
fail(String) |
Let the method fail, might be usable to check that a certain part of the code is not reached. |
assertTrue(true); |
True |
assertsEquals([String message], expected, actual) |
Test if the values are the same. Note: for arrays the reference is checked not the content of the arrays |
assertsEquals([String message], expected, actual, tolerance) |
Usage for float and double; the tolerance are the number of decimals which must be the same |
assertNull([message], object) |
Checks if the object is null |
assertNotNull([message], object) |
Check if the object is not null |
assertSame([String], expected, actual) |
Check if both variables refer to the same object |
assertNotSame([String], expected, actual) |
Check that both variables refer not to the same object |
assertTrue([message], boolean condition) |
Check if the boolean condition is true. |
try {a.shouldThroughException(); fail("Failed")} catch (RuntimeException e) {asserttrue(true);} |
Alternative way for |
-
Links and Literature
http://www.junit.org JUnit Homepage
http://junit.sourceforge.net/doc/testinfected/testing.htm JUnit Test Infected: Programmers Love Writing Tests
http://junit.sourceforge.net/doc/cookbook/cookbook.htm The JUnit Cookbook from Erich Gamma and Kent Beck