JUnit4小白入門

醬油能發表於2018-03-19

編寫一個需要測試的類

package martin;

public class Calculator {

    private static int result; // 靜態變數,用於儲存執行結果

    public void add(int n) {
        result = result + n;
    }

    public void substract(int n) {
        result = result - n;  //Bug: 正確的應該是 result =result-n
    }

    public void multiply(int n) {
        // 此方法尚未寫好
    }

    public void divide(int n) {
        result = result / n;
    }

    public void square(int n) {
        result = n * n;
    }

    public void squareRoot(int n) {
        // for (; ;) ;            //Bug : 死迴圈
        result = (int)Math.sqrt(n);
    }

    public void clear() {     // 將結果清零
        result = 0;
    }

    public int getResult() {
        return result;
    }
}

編寫測試類

package martin;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

public class CalculatorTest {

    private static Calculator calculator = new Calculator();

    @Before
    public void setUp() throws Exception {
        calculator.clear();
    }

    @Test
    public void testAdd() {
        calculator.add(2);
        calculator.add(3);
        assertEquals(5,  calculator.getResult());
    }

    @Test
    public void testSubstract() {
        calculator.add(10);
        calculator.substract(2);
        assertEquals(8, calculator.getResult());
    }

    @Ignore("Multiply() Not yet implemented")
    @Test
    public void testMultiply() {

    }

    @Test
    public void testDivide() {
        calculator.add(8);
        calculator.divide(2);
        assertEquals(4, calculator.getResult());
    }

    @Test(timeout = 1000)
    public void squareRoot() {
        calculator.squareRoot(4);
        assertEquals(2, calculator.getResult());
    }

    @Test(expected = ArithmeticException.class)
    public void divideByZero() {
        calculator.divide(0);
    }

}

相關文章