清單 5. 多線程運行測試案例結果
[concurrent] Started running samples.SimpleTestClasssamples.SimpleTestClasstestAtestAtestAtestAtestAtestAtestAtestAtestAtestAtestA() - [405.0ms]testB() - [469.0ms]testC() - [503.0ms]total: 3, failures:0 (GREEN) - 1447.0ms
是否和想象中的一樣?默認情況 p-unit 啟動 10 個線程來執行,要指定不同的線程數,只需將線程數做為參數傳入 PUnitConcurrentRunner 即可。p-unit 甚至支持不同的測試案例有不同的線程數,這要求測試案例實現 p-unit 中定義的 Concurrent 接口,該接口的定義為:
清單 6. p-unit Concurrent 接口
public interface Concurrent { public int concurrentCount();}
該接口的意思,相信無需再多做解釋了,返回該測試案例需要的線程數。
參數化測試案例
性能測試,不同于單元測試,經常要求測試不同數量級在同一個測試場景中的表現,JUnit 是一款非常優秀的單元測試工具,但沒覆蓋到這個方面。比如我們比較類庫 Foo1 的方法 bar() 和類庫 Foo2 的方法 bar() 哪個更符合自己的應用程序,我們需要測試該函數在應用程序可能的數量級的范圍內的表現。有經驗的開發者知道經常碰到在小數量級 A 更好大數量級 B 更好的局面,因此全面的測試對于代碼的性能理解非常重要,能幫助開發者做出正確的決定。p-unit 支持將參數傳給測試方法,測試案例需要實現 p-unit 的 parameterizable 接口,該接口的主要方法是返回一組參數列表,這組列表的參數將會一一傳給測試方法。
清單 7. p-unit 參數化測試案例
public class ParamTestClass implements Parameterizable { public static void main(String[] args) { new PUnitSoloRunner().run(ParamTestClass.class); } public Parameter[] parameters() { return new Parameter[] { new ParameterImpl(10), new ParameterImpl(20) }; } public void testA(ParameterImpl param) { SampleUtil.doSomething(); } public void testB(ParameterImpl param) { SampleUtil.doSomething(); } public void testC(ParameterImpl param) { SampleUtil.doSomething(); } public void setUpAfterWatchers(Parameter param) throws Exception { } public void setUpBeforeWatchers(Parameter param) throws Exception { } public void tearDownAfterWatchers(Parameter param) throws Exception { } public void tearDownBeforeWatchers(Parameter param) throws Exception { } static class ParameterImpl implements Parameter { private int _count; ParameterImpl(int count) { _count = count; } public int count() { return _count; } public String toString() { return String.valueOf(_count); } }}
上述代碼的執行結果為:
清單 8. p-unit 參數化測試案例輸出
[solo] Started running samples.ParamTestClasssamples.ParamTestClasstestA(10) - [57936.0bytes,447.0ms]testA(20) - [33128.0bytes,61.0ms]testB(10) - [24832.0bytes,137.0ms]testB(20) - [0.0bytes,63.0ms]testC(10) - [83560.0bytes,468.0ms]testC(20) - [16528.0bytes,47.0ms]total: 6, failures:0 (GREEN) 1450.0ms
從上述結果看出,每個方法被執行了 2 次,每次傳入不同的參數。多線程運行參數化測試程序?相信讀者已經明白怎么去實現了,只需將 PUnitSoloRunner 替換成 PUnitConcurrentRunner。
原文轉自:http://www.anti-gravitydesign.com