IBM®
메인 컨텐츠로 가기
    Korea [국가변경]    이용약관
 
 
   
        제품    서비스 & 솔루션    고객지원 & 다운로드    회원 서비스    
메인 컨텐츠로 가기

한국 developerWorks  >  자바  >

JUnit 4로 뛰어들기

자바 5 주석을 사용한 효율적인 테스트

developerWorks
Go to the previous page11 페이지 중 4 페이지Go to the next page

문서 옵션

토론


제안 및 의견
피드백

튜토리얼 평가

이 컨텐츠를 개선하기 위한 도움을 주십시오.


테스트 픽스쳐

테스트 픽스쳐는 JUnit 4의 새로운 기능은 아니지만 픽스쳐 모델이 새롭게 향상되었다. 이 섹션에서는 픽스쳐를 사용하는 이유와 경우에 대해 설명하고 이전 버전의 유연하지 않은 픽스쳐와 JUnit 4의 새로운 모델 간의 차이점을 설명한다.

픽스쳐를 사용하는 이유

픽스쳐는 특정 로직이 테스트 전후에 실행되도록 보장하는 하나의 약정이므로 손쉽게 재활용할 수 있다. 이전 버전의 JUnit에서 이 약정은 픽스쳐를 구현했는지 여부에 관계없이 적용되었다. 하지만 JUnit 4에서 픽스쳐는 주석을 통해 명시적으로 변경되므로 사용자가 픽스쳐를 사용하도록 결정한 경우에만 약정이 적용된다.

테스트 전후에 픽스쳐를 실행할 수 있도록 보장하는 약정을 통해 재사용이 가능한 로직을 코딩할 수 있다. 예를 들어 이러한 로직은 여러 테스트 케이스 또는 로직에서 데이터 종속 테스트를 실행하기 전에 데이터베이스를 채우도록 테스트를 수행할 클래스를 초기화할 수 있다. 이러한 테스트 케이스는 공통 로직을 사용하므로 어느 쪽이든 픽스쳐를 사용하면 테스트 케이스를 더 쉽게 관리할 수 있다.

픽스쳐는 동일한 로직을 사용하는 여러 테스트를 실행 중이고 이들 중 일부 또는 전체가 실패할 경우에 특히 유용하다. 각 테스트의 설정 로직에서 실패 원인을 확인하는 대신 한 곳에서 실패 원인을 추론할 수 있다. 또한 테스트가 일부만 성공하고 일부는 실패하는 경우 이러한 실패의 공통 원인으로 픽스쳐 로직을 검사하지 않아도 된다.




위로


유연하지 않은 픽스쳐

O이전 버전의 JUnit에서는 다소 유연하지 않은 픽스쳐 모델이 사용되었다. 여기에서는 setUp()tearDown() 메서드를 사용하여 모든 테스트 메서드를 래핑해야 했다. Listing 8에서는 이러한 모델의 잠재적인 단점을 확인할 수 있다. 여기에서는 setUp() 메서드가 구현되며 따라서 정의된 각 테스트에 대해 한 번씩 두 번 실행된다.


Listing 8. 유연하지 않은 픽스쳐
                    
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import junit.framework.TestCase;

public class RegularExpressionTest extends TestCase {

 private String zipRegEx = "^\\d{5}([\\-]\\d{4})?$";
 private Pattern pattern;

 protected void setUp() throws Exception {
  this.pattern = Pattern.compile(this.zipRegEx);
 }

 public void testZipCodeGroup() throws Exception{		 
  Matcher mtcher = this.pattern.matcher("22101-5051");
  boolean isValid = mtcher.matches();			
  assertEquals("group(1) didn't equal -5051", "-5051", mtcher.group(1));
 }

 public void testZipCodeGroupException() throws Exception{		 
  Matcher mtcher = this.pattern.matcher("22101-5051");
  boolean isValid = mtcher.matches();			
  try{
   mtcher.group(2);
   fail("No exception was thrown");
  }catch(IndexOutOfBoundsException e){
  }
 }
}




위로


해결 방법

이전 버전의 JUnit에서는 TestSetup 데코레이터를 사용하여 픽스쳐가 한 번만 실행되도록 지정할 수 있었지만 Listing 9와 같이 이러한 방식은 번거로운 작업이다(필수 suite() 메서드 참조):


Listing 9. JUnit 4 이전의 TestSetup
                    
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

public class OneTimeRegularExpressionTest extends TestCase {

 private static String zipRegEx = "^\\d{5}([\\-]\\d{4})?$";
 private static Pattern pattern;

 public static Test suite() {
  TestSetup setup = new TestSetup(
    new TestSuite(OneTimeRegularExpressionTest.class)) {
     protected void setUp() throws Exception {
      pattern = Pattern.compile(zipRegEx);
    }
   };
  return setup;
 }

 public void testZipCodeGroup() throws Exception {
  Matcher mtcher = pattern.matcher("22101-5051");
  boolean isValid = mtcher.matches();
  assertEquals("group(1) didn't equal -5051", "-5051", mtcher.group(1));
 }

 public void testZipCodeGroupException() throws Exception { 
  Matcher mtcher = pattern.matcher("22101-5051");
  boolean isValid = mtcher.matches();
  try {
   mtcher.group(2);
   fail("No exception was thrown");
  } catch (IndexOutOfBoundsException e) {
  }
 }
}

JUnit 4 이전에는 픽스쳐의 이점을 얻기 위해서는 감수해야 하는 희생이 더 많았다.




위로


4.0에서의 유연성

JUnit 4에서는 주석을 사용하여 픽스쳐에 따른 상당한 오버헤드를 없앰으로써 모든 테스트에 대해 또는 전체 클래스에 대해 한 번 픽스쳐를 실행하거나 아예 실행하지 않을 수도 있다. 픽스쳐 주석은 클래스 수준의 픽스쳐 2개와 메서드 수준의 픽스쳐 2개가 존재한다. 클래스 수준의 경우 @BeforeClass@AfterClass가 있으며 메서드(또는 테스트) 수준의 경우 @Before@After가 있다.

Listing 10의 테스트 케이스에는 @Before 주석을 사용하여 두 테스트에 대해 실행되는 픽스쳐가 들어 있다.


Listing 10. 주석을 사용한 유연한 픽스쳐
                    
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;

public class RegularExpressionJUnit4Test {
 private static String zipRegEx = "^\\d{5}([\\-]\\d{4})?$";
 private static Pattern pattern;

 @Before
 public static void setUpBeforeClass() throws Exception {
  pattern = Pattern.compile(zipRegEx);
 }

 @Test
 public void verifyZipCodeNoMatch() throws Exception{		
  Matcher mtcher = this.pattern.matcher("2211");
  boolean notValid = mtcher.matches();		
  assertFalse("Pattern did validate zip code", notValid);
 }

 @Test(expected=IndexOutOfBoundsException.class)
 public void verifyZipCodeGroupException() throws Exception{		
  Matcher mtcher = this.pattern.matcher("22101-5051");
  boolean isValid = mtcher.matches();			
  mtcher.group(2);		
 }
}




위로


1회용 픽스쳐

픽스쳐를 한 번만 실행해야 하는 경우는 어떻게 해야 할까? Listing 9처럼 이전 스타일의 데코레이터를 구현하는 대신 Listing 11에서와 같이 @BeforeClass 주석을 사용할 수 있다.


Listing 11. JUnit 4에서 1회용 픽스쳐 설정
                    
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;

public class RegularExpressionJUnit4Test {
 private static String zipRegEx = "^\\d{5}([\\-]\\d{4})?$";
 private static Pattern pattern;

 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
  pattern = Pattern.compile(zipRegEx);
 }

 @Test
 public void verifyZipCodeNoMatch() throws Exception{		
  Matcher mtcher = this.pattern.matcher("2211");
  boolean notValid = mtcher.matches();		
  assertFalse("Pattern did validate zip code", notValid);
 }

 @Test(expected=IndexOutOfBoundsException.class)
 public void verifyZipCodeGroupException() throws Exception{		
  Matcher mtcher = this.pattern.matcher("22101-5051");
  boolean isValid = mtcher.matches();			
  mtcher.group(2);		
 }
}

tearDown() 메서드

이전의 tearDown() 기능은 새로운 픽스쳐 모델에서 사라지지 않았다. tearDown()메서드를 실행하려면 새 메서드를 생성하고 필요에 따라 @After 또는 @AfterClass를 사용하면 된다.




위로


향상된 사용성

JUnit 4에서는 테스트 케이스에서 두 개 이상의 픽스쳐를 지정할 수 있다. 새로운 주석 중심의 픽스쳐에서는 여러 @BeforeClass 픽스쳐 메서드를 만드는 데 어떠한 제한도 없다. 하지만 현재 버전의 JUnit 4에서는 어떤 픽스쳐 메서드를 먼저 실행하도록 지정할 수 없으므로 두 개 이상의 픽스쳐를 사용할 때 이 점에 주의해야 한다.




위로



Go to the previous page11 페이지 중 4 페이지Go to the next page
    IBM 소개 개인정보 보호정책 문의