junit 지원 라이브러리 소개

23
JUNIT 지지 지지지지지 지지 2015.07 Hyunil Shin 1

Upload: hyunil-shin

Post on 16-Apr-2017

485 views

Category:

Engineering


8 download

TRANSCRIPT

1

JUNIT 지원 라이브러리 소개2015.07Hyunil Shin

목차1. 비동기 테스트 , Awaitility2. 병렬 수행3. 매개변수 실행4. 반복 수행5. assertThat6. Maven 연동7. Jenkins 연동8. 기타

3

1. Awaitility• https://code.google.com/p/awaitility/• 비동기 동작 테스트에 사용• 특정 시간 동안 polling 방식으로 Callable 함수를 호출• Callable 함수 return 방법

• 원하는 값을 확인한 경우 : return true• 예외 강제 발생 : throw Exception• Timeout : ConditionTimeoutException 발생

Callable<Boolean> xxx() { // 조건에 맞으면 return true; // 이상 현상이면 throw Exception; // else return false; // 계속 반복한다 .}

4

기타• timeout 이 발생하면 ConditionTimeoutException 이

발생한다 .• ConditionTimeoutException 을 catch 하여 디버깅에 필요한 정보를

출력할 수 있다 .

• Callable 에서 Exception 을 던지는 경우 어느 지점 ( 코드 ) 에서 발생하였는지 알 수 없다 .• Callable 함수를 호출하는 곳에서 try-catch 를 사용하면 발생

지점을 추적할 수 있다 .

5

2. 테스트 병렬 수행하기• 클래스 내 모든 test method 를 병렬로 실행하여 테스트

수행 속도를 높인다 .

• 주의사항• @BeforeClass 는 한번만 실행되고 , @Before, @After 도 병렬로

실행된다 .• conflict 과 test data 의 충돌이 없어야 함

• ex) 동일한 테스트 계정 사용으로 인한 충돌

import com.google.code.tempusfugit.concurrency.ConcurrentTestRunner;

@RunWith(ConcurrentTestRunner.class)public class BasicTest1 {

6

3. 매개변수 실행• https://github.com/Pragmatists/JUnitParams/wiki/Quickstart• 동일 테스트 코드에 input data 만 다르게 적용

import junitparams.JUnitParamsRunner;import junitparams.Parameters;import static junitparams.JUnitParamsRunner.$;

@RunWith(JUnitParamsRunner.class)public class YYY {

private static final Object[] getStrangeCharacter() {return $(

$("%"),$("&"),$("''"),$("/"));

}

@Parameters(method = "getStrangeCharacter")public void xxxx(String subject) throws Exception {

7

매개변수 실행 in Jenkins• Input 개수만큼 test method 가 수행된 것으로 결과가

나타난다 .

• 테스트 결과에 테스트에 사용된 Input 이 포함된다 .• Ex) [0] % ([test method]) Passed [1] ? ([test method]) Failed

• 테스트 실패가 발생한 Input 을 금방 알 수 있다 .

8

4. 테스트 반복 수행 - 단순히 반복하기• 단순한 테스트를 반복하는 경우• http://

www.javacodegeeks.com/2013/10/write-effective-load-tests-using-junit-and-repeat-annotation.html

import org.easetech.easytest.annotation.Repeat;import org.easetech.easytest.runner.DataDrivenTestRunner;

@RunWith(DataDrivenTestRunner.class)//DataDrivenTestRunner 를 사용하면 특정 test method 실행이 되지 않는다 . mvn test -Dtest=xxx#yyy 를 적용할 수 없다 .

public class YYY {

/** * mvn test -Dtest.repeatCount=x 로 하면 x 번 실행됨 */@Test @Repeat(times=1)public void xxx() throws Exception {

※ 반복 수행을 위한 다른 방법들도 있지만 횟수를 동적으로 조정할 수 방법은 이것이 유일한 것 같다 .

9

Jenkins 수행 결과• 횟수만큼 가상의 test method 가 생성된다 .

• ex) xxxx_0, xxxx_1, xxxx_2

• 동일한 test method 로 인식되지 않기 때문에 성능 trend를 보기에는 적합하지 않다 .• Ex) 10 번 반복하면 10 개의 다른 테스트가 수행된 것으로 나타난다 .

10

테스트 반복 수행 - Concurrent• http://tempusfugitlibrary.org/documentation/junit/load/• (Concurrent 개수 X 반복횟수 ) 만큼 반복 수행

import com.google.code.tempusfugit.concurrency.ConcurrentRule;import com.google.code.tempusfugit.concurrency.ConcurrentTestRunner;import com.google.code.tempusfugit.concurrency.RepeatingRule;import com.google.code.tempusfugit.concurrency.annotations.Concurrent;import com.google.code.tempusfugit.concurrency.annotations.Repeating;

@RunWith(ConcurrentTestRunner.class)public class ProvisionServerCacheUpdate_RepeatConcurrently {

@Rule public RepeatingRule rule = new RepeatingRule();@Rule public ConcurrentRule concurrently = new ConcurrentRule();

@Test@Concurrent (count = 5) // 동시에 testA() 를 5 개 실행한다 .@Repeating (repetition = 2) // 2 번씩 반복한다 . 총 10 번 testA 가 수행된다 .public void testA() throws Exception {

11

테스트 반복 수행 - Concurrent• 간헐적으로 실패하는 경우 반복 수행하여 재현 가능성을

높인다 .

• 특이사항• 몇 번을 수행하던 결과에는 하나의 테스트로 나타난다 .• 수행 도중 실패가 발생하면 즉시 테스트가 종료한다 .

• 반복횟수가 남아 있어도 더 이상 수행하지 않는다 .

12

5. assertThat• assert 문장과 실패 메시지를 보다 readable 하게 한다 .

assertTrue(resultContent.contains("1ActiveSquare"));

assertThat(resultContent).contains("1ActiveSquare");

Failure Trace- java.lang.AssertionError

Failure Trace- java.lang.AssertionError: expect-ing: <‘hello!!!’> to contains: <‘1Ac-tiveSquare’>

13

assertThat Examples• assertThat(contentString).contains(footer);

• assertThat(xxx).as(“description").doesNotHaveDuplicates();

• assertThat(xxx).as(“description").containsAll(yyy);

• assertThat(msgs.get(0).getArray()).hasSize(1);

14

assertThat 라이브러리• FEST

• https://code.google.com/p/fest/

• Truth• https://google.github.io/truth/

• Hamcrest• https://code.google.com/p/hamcrest/wiki/Tutorial

15

6. Maven 연동// Maven 으로 테스트 실행하기

mvn -U clean test -P $SET // Profile 선택-Dgroups=[CategoryClass] // 테스트 대상-Denv=$env // 매개변수-------------------------------------------------------------------------------// 테스트 코드에서 매개변수 조회하기

AA = Long.parseLong(System.getProperty(“env"));

16

7. Jenkins 연동 - 테스트 결과 Aggre-gate• 다수의 Test Job 이 있는 경우 테스트 결과를 Aggregate

할 필요가 있다 .• 테스트 결과를 한꺼번에 보고 싶은 때

• ( 조금 무식한 방법 ) Copy Artifact plugin을 이용하여 테스트 결과 파일 (xml) 을 모은다 .• 매개변수로 필터링 하여 특정 Build 의 결과를 모을 수 있다 .

17

7. Jenkins 연동 - 성능 Trend• 동일한 조건 ( 부하 ) 으로 장기간 테스트를 반복하면서 re-

sponding time trend 를 살펴볼 수 있다 .• Performance 플러그인

8. 기타 - 동적으로 테스트 Ignore 처리• http://www.codeaffine.com/2013/11/18/a-junit-rule-to-con-

ditionally-ignore-tests/

• assumeTrue 를 사용하면 되나 skip 시 eclipse, maven에서는 pass 로 나타남

• setUp 에서는 assumeTrue 를 사용하면 skip 으로 나타남

8. 기타 - HTML 파싱• Jsoup 라이브러리 사용

import org.jsoup.Jsoup;

int imgCount = Jsoup.parse(resultContent, "UTF-8").select("img").size();assertThat(imgCount).as(" 이미지 개수 ").isEqualTo(9);for(int i = 0; i < imgCount; i++) { String imgsrc = Jsoup.parse(resultContent, "UTF-8").select("img").get(i).attr("src"); System.out.println("imgsrc: " + imgsrc); assertThat(imgsrc).contains(xxx);}

8. 기타 - JUnit Rules// 테스트 함수명을 변수로 활용하는 경우@Rulepublic TestName testName = new TestName();

String xxx = testName.getMethodName();

// 첨부파일 만들기@Rulepublic TemporaryFolder tmpFolder = new TemporaryFolder();

File tempFile = tmpFolder.newFile();RandomString rs = new RandomString(1024);FileUtils.write(tempFile, rs.nextString());for(int i = 0; i < kbytes - 1; i++) {FileUtils.write(tempFile, rs.nextString(), true);}return tempFile.getAbsolutePath();

향후 시도 해 볼만 한 것들• 멀티쓰레드 동작 개선

• https://junit-toolbox.googlecode.com/git/javadoc/com/googlecode/junittoolbox/MultithreadingTester.html

• (Jenkins) 테스트 실패 유형 한 눈에 파악하기• 테스트 실패가 많은 경우에 적용• Error 메시지로 테스트 실패 그룹핑 ( 현재 Jenkins 에서는

지원하지 않음 )• 방법 : Jenkins REST API 를 이용하여 테스트 결과를 가져와서 파싱

후 Error 메시지로 그룹핑

23

END