2021년 12월 29일 수요일

Android를 위한 JUnit test suite 샘플

 우리는 app/src/main/java 에 더하기와 곱셈을 위한 두 개의 static method를 갖는 Calculator class를 만들 것이다. 그리고 app/src/test/java 에 calculater 클래스에 있는 두 개의 static method를 테스트하기 위한 두 개의 test class를 만들 것이다.

코드를 작성하기 전에, 아래와 같이 junit 을 위한 gradle dependency를 추가한다.

dependencies {
    //Other dependencies.....
    //junit test compile dependency
    testCompile 'junit:junit:4.12'
}

1. Calculator.java 파일을 생성한다.

public class Calculator {

    public static int addition(int a, int b) {
        return a + b;
    }

    public static int multiplication(int a, int b) {
        return a * b;
    }

}

2. 테스트 패키지에 AddtionTest.java 를 생성한다. 이 패키지를 보이게 하려면, Build Variants를 Unit Tests로 변경한다. 모든 테스트 클래스들은 이 패키지 아래에 있다.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import static org.junit.Assert.*;
public class AdditionTest {
    @Test
    public void additionTest() throws Exception {
        //Fail this on purpose
        int expected = 5;
        int actual = Calculator.addition(2, 2);
        assertEquals(expected, actual);
    }
}

3. 테스트 패키지에 MultiplicationTest.java 를 생성한다.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import static org.junit.Assert.*;

public class MultiplicationTest {
    @Test
    public void multiplicationTest() throws Exception {
        int expected = 6;
        int actual = Calculator.multiplication(2, 3);
        assertEquals(expected, actual);
    }
}

4. 마지막으로, 위의 두 테스트를 하나의 테스트 슈트에 넣어서 한번에 테스트들을 수행하도록 할 것이다. MyTestSuite.java 라고 하는 Test suite 클래스를 만든다.

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
        AdditionTest.class,
        MultiplicationTest.class
})
public class MyTestSuite {
}

4. MyTestSuite 클래스에서 우클릭해서 Run ‘MyTestSuite’ 를 선택한다.

5. 윈도우 커맨드 창을 열어 프로젝트 루트 디렉토리에서도 실행할 수 있다. 명령행에서 실행하면 MyTestSuite 클래스 조차 필요없다.

./gradlew test

댓글 없음: