用Eclipse進行單元測試JUnit4


(1)在項目中引入Jar包

(2)編寫需要測試的類

public class Calculator {
     private static int result=0; // 靜態變量,用於存儲運行結果
        public int add(int n) {
            result = result + n;
            return result;
        }
        public void substract(int n) {
            result = result - 1;  //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 : 死循環
        }
        public void clear() {     // 將結果清零
            result = 0;
        }
        public int getResult() {
            return result;
        }
}

(3)將鼠標點在要測試的類上單擊->new->JUnit Test Case

(4)勾選要測試的方法

(5)測試方法生成

(6)修改測試方法體

public class CalculatorTest {

    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void testAdd() {
        Calculator cal = new Calculator();
        int result = cal.add(5);
        Assert.assertEquals("加法有問題",5, result);
        //fail("Not yet implemented");
    }

    @Test
    public void testSubstract() {
        fail("Not yet implemented");
    }

    @Test
    public void testMultiply() {
        fail("Not yet implemented");
    }

    @Test
    public void testDivide() {
        fail("Not yet implemented");
    }

    @Test
    public void testSquare() {
        fail("Not yet implemented");
    }

    @Test
    public void testSquareRoot() {
        fail("Not yet implemented");
    }

    @Test
    public void testClear() {
        fail("Not yet implemented");
    }

    @Test
    public void testGetResult() {
        fail("Not yet implemented");
    }

}
(7)在生成的測試類的測試方法上單擊->run as ->JUnit Test


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM