본문 바로가기

Junit/Mockito

[JUnit] 간단 정리

 

JUnit은 테스트 모듈이다.

일반적으로 System.out.println등을 사용하는 테스트는 각 클래스에 main메서드등을 만들어야하며

테스트가 끝나면 다시 지워주고, 게다가 테스트의 이력관리가 전혀 되지 않는 단점이 있다.


다음과 같은 클래스를 만들었다고 하면

 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package helloproject.junit1;

import java.util.Calendar;

/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class DayCounter {
 public int MILLIS_PER_DAY = 1000*60*60*24;
 private Calendar day1 = null;
 private Calendar day2 = null;
 
 public void setDay1(Calendar day){
  this.day1 = day;
 }
 
 public Calendar getDay1(){
  return day1;
 }
 
 public void setDay2(Calendar day){
  this.day2 = day;
 }
 
 public Calendar getDay2(){
  return day2;
 }
 
 public long getDays(){
  long l_remain_date = day1.getTime().getTime() - day2.getTime().getTime();
 
  long remain_date = l_remain_date/MILLIS_PER_DAY;
  return remain_date;
 }
}


이여기서 getDays메서드를 테스트 해보기 위해선 main메서드를 추가하고,

해야하는 번거로움이 있었으며, 끝나면 다시 지워야만 했었다.


Junit을 이용한 테스트 클래스 작성

package helloproject.junit1;

import java.util.Calendar;
import junit.framework.TestCase;

/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class DayCounterTest1 extends TestCase {
 public void testGetDays(){
  DayCounter counter = new DayCounter();
  Calendar day = Calendar.getInstance();
  day.set(2003,10,5);
  counter.setDay1(day);
 
  day = Calendar.getInstance();
  day.set(2002,6,2);
  counter.setDay2(day);
 
  assertTrue(counter.getDays() > 500);
 }

}


TestCase를 상속받은 클래스를 만들어 test로 시작하는 메서드를 작성만 해주면 된다.

실행시 걸린 시간도 표시가 된다.


실행방법은

javac -classpath .... DayCounterTest1.java

java -cp ..junit.jar의 경로 junit.textui.TestRunner 패키지.DayCounterTest1


TestSuite클래스는 TestCase로 이루어진 각각의 테스트 클래스들을 하나로 묶어 한번에 실행하거나 특정한 test메소드만 실행하고 싶을때 사용한다.


public class AllTests {

 public static Test suite() {
  TestSuite suite = new TestSuite("Test for helloproject.junit1");
  //$JUnit-BEGIN$
  suite.addTestSuite(DayCounterTest1.class);
  suite.addTestSuite(DayCounterTest2.class);
  //$JUnit-END$
  return suite;
 }
}


이런식으로 사용하며, 테스트Case 클래스를 등록 후 suite값을 리턴해주는 방식이다.



java로 실행 시 들어가있던 TestRunner클래스는 ui를 선택할 수 있도록 하기 위한 것이다.

textui, swingui,awtui를 선택 할 수 있으며, 결과값이 선택된 ui에 따라 다르게 나타난다.


또한 TestRunner는 원하는 곳에서 호출이 가능하다.

본래 위의 AllTest클래스를 실행하기 위해서는

java -cp .;d:\junit.jar의 경로 junit.awtui.TestRunner AllTest 이런식으로 해줘야 하지만


아래의 main메소드를 AllTest클래스에 추가하면

public static void main(String args[]){

 junit.swingui.TestRunner.run(AllTest.class);

}


다음과 같이 실행을 하면 swingui로 결과를 얻을 수 있다.

java -p .;d:\junti.jar의 경로 AllTest


TestCase 클래스는 각 test메소드 실행마다 Test클래스의 인스턴스를 초기화한다.

(필드변수의 값이 매번 초기화 된다는 뜻)


클래스의 인스턴스가 생성된 후에 새로운 값을 초기화하고자 한다면,

setUp()메소드와 tearDown()메소드를 재정의 하면 가능하다.


test메소드전에 setUp메소드가 호출되므로, x의 값이 원하는 값으로 셋팅됨을 알 수 있다.


Ant와 JUnit

<junit> 태스크


build.xml에

<target name="test" depends="compile">
 <junit printsummary="true" haltonfailure="no">
  <classpath>
   <pathelement path="${classes.dir}"/>
  </classpath>
  <formatter type="xml"/>
  <batchtest todir="${test.dir}">
   <fileset dir="${classes.dir}">
    <include name="**/*Test*.class"/>
   </fileset>
  </batchtest>
  <test name="helloproject.jnuit1.DayCounterTest1"/>
 </junit>

</target>를 추가 후


ant -f build-test.xml (f는 다른이름으로 만든 빌드파일을 실행하고자 할때 사용)

를 실행하면 빌드를 하기전 테스트를 실행하고 haltonfailure="no" 의 값에 따라

테스트 실패에 따라 빌드를 하거나 빌드를 하지 않게 된다.



<junitreport> 태스크

<junitreport todir="${test.dir}">
 <fileset dir="${test.dir}">
 <include name="TEST **.xml"/>
 </fileset>
 <report format="frames" todir="${test.dir}/html"/>
</junitreport>

를 test target안에 추가하면 test.dir에 생성된 TEST로 시작하는 xml 파일을 병합하여

TEST-TestSuties.xml파일을 생성하고 test.dir/html디렉토리에 결과 리포트를

html 문서로 자동 생성 시켜준다.