Java數據庫開發與實戰運用---Junit

單元測試

 

使用main方法

單元測試的好處

 

JUnit

Junit特點

Junit的設計

 

 

使用Assert斷言

使用Before和After

 

異常測試

修改代碼

然後測試會通過

參數化測試

超時測試

package com.feiyangedu.sample;

public class PI {

	// π/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9 - ...
	public double calculate(int count) {
		double sum = 0;
		boolean positive = true;
		int n = 0;
		for (int i = 1;; i += 2) {
			sum = sum + (positive ? 4.0 : -4.0) / i;
			positive = !positive;
			n++;
			if (n == count) {
				break;
			}
		}
		return sum;
	}

}
package com.feiyangedu.sample;

import static org.junit.Assert.*;

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

public class PITest {

	PI pi;

	@Before
	public void setUp() throws Exception {
		pi = new PI();
	}

	@Test(timeout = 500)
	public void test1k() {
		double r = pi.calculate(1000);
		assertEquals(3.14, r, 0.01);
	}

	@Test(timeout = 500)
	public void test1m() {
		double r = pi.calculate(1000000);
		assertEquals(3.1416, r, 0.0001);
	}

	@Test(timeout = 500)
	public void test100m() {
		double r = pi.calculate(100000000);
		assertEquals(3.14159, r, 0.00001);
	}

}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章