以下的例子是測試單元測試ExampleTestCase.testOneSecondResponse()方法對應(yīng)的功能的一個負(fù)載測試,用來測試該功能的執(zhí)行效率。其中有10個并發(fā)用戶,無延遲,每個用戶只運行一次。LoadTest本身使用了TimedTest來得到在負(fù)載情況下ExampleTestCase.testOneSecondResponse()方法的實際運行能力。如果全部的執(zhí)行時間超過了1.5秒則視為不通過。10個并發(fā)處理在1.5秒通過才算通過。
負(fù)載下承受能力測試舉例
import com.clarkware.junitperf.*;
import junit.framework.Test;
public class ExampleThroughputUnderLoadTest {
public static Test suite() {
int maxUsers = 10;
long maxElapsedTime = 1500;
Test testCase = new ExampleTestCase("testOneSecondResponse");
Test loadTest = new LoadTest(testCase, maxUsers);
Test timedTest = new TimedTest(loadTest, maxElapsedTime);
return timedTest;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}
在下面的例子中,測試被顛倒過來了,TimedTest度量ExampleTestCase.testOneSecondResponse()方法的執(zhí)行時間。然后LoadTest中嵌套了TimedTest來仿效10個并發(fā)用戶執(zhí)行ExampleTestCase.testOneSecondResponse()方法。如果某個用戶的執(zhí)行時間超過了1秒則視為不通過。
負(fù)載下響應(yīng)時間測試舉例
import com.clarkware.junitperf.*;
import junit.framework.Test;
public class ExampleResponseTimeUnderLoadTest {
public static Test suite() {
int maxUsers = 10;
long maxElapsedTime = 1000;
Test testCase = new ExampleTestCase("testOneSecondResponse");
Test timedTest = new TimedTest(testCase, maxElapsedTime);
Test loadTest = new LoadTest(timedTest, maxUsers);
return loadTest;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}
性能測試套件
下面的測試用例例子中把ExampleTimedTest和ExampleLoadTest結(jié)合在一個測試套件中,這樣可以自動地執(zhí)行所有相關(guān)的性能測試了:
Example Performance Test Suite
import junit.framework.Test;
import junit.framework.TestSuite;
public class ExamplePerfTestSuite {
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTest(ExampleTimedTest.suite());
suite.addTest(ExampleLoadTest.suite());
return suite;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}