junit 循环测试_重复运行JUnit测试而没有循环
junit 循環測試
最近,我遇到了一個問題,我不得不編寫一種方法的測試,該方法需要計算在一定可能性范圍內的隨機分布值1 。 更準確地說,如果您假設簽名看起來像
測試可能會驗證以下2個 :
public class RandomRangeValueCalculatorImplTest {@Testpublic void testCalculateRangeValue() {long center = [...];long radius = [...];RangeValueCalculator calculator = [...];long actual = calculator.calculateRangeValue( center, radius );assertTrue( center + radius >= actual );assertTrue( center - radius <= actual );} }但是,多次計算相同的中心和半徑的范圍值將返回不同的結果(至少在大多數情況下)。 因此,從某種意義上來說,解決方案在某種程度上是脆弱的,即實施不善可能會輕易導致間歇性故障。 另一方面,我不想深入到實際破壞值分配的深度。 后者(隨機,高斯等)由協作者提供,并且其正確用法已通過其他測試確認。
在我看來,一種更為實用的解決方案可能是一次又一次地實際自動運行上述測試,以使其更加“有意義”。 當然,最簡單的方法是將測試內容放入一個循環中并繼續進行下去。
但是首先,將斷言放在一個循環中并將兩個方面混合到一個測試運行中似乎有些不對。 更為重要的是,涵蓋的問題域需要進行更多種類的測試。 因此,出于減少冗余的意圖,我記得關于JUnit-Rules的帖子,并實現了一個簡單的重復規則3 。 有了這個規則,上面的測試可以輕輕地修改為:
public class RandomRangeValueCalculatorImplTest {@Rulepublic RepeatRule repeatRule = new RepeatRule();@Test@Repeat( times = 10000 )public void testCalculateRangeValue() {long center = [...];long radius = [...];RangeValueCalculator calculator = [...];long actual= calculator.calculateRangeValue( center, radius );assertTrue( center + radius >= actual );assertTrue( center - radius <= actual );} }我認為很容易理解testCalculateRangeValue方法在運行測試用例時將執行10000次。 以下代碼片段顯示了RepeatRule的實現,這很簡單:
public class RepeatRule implements TestRule {@Retention( RetentionPolicy.RUNTIME )@Target( {java.lang.annotation.ElementType.METHOD} )public @interface Repeat {public abstract int times();}private static class RepeatStatement extends Statement {private final int times;private final Statement statement;private RepeatStatement( int times, Statement statement ) {this.times = times;this.statement = statement;}@Overridepublic void evaluate() throws Throwable {for( int i = 0; i < times; i++ ) {statement.evaluate();}}}@Overridepublic Statement apply(Statement statement, Description description ){Statement result = statement;Repeat repeat = description.getAnnotation( Repeat.class );if( repeat != null ) {int times = repeat.times();result = new RepeatStatement( times, statement );}return result;} }到目前為止,RepeatRule達到了目的,并且基于上述實現的系統功能正在發揮作用。 盡管如此,有時有人會為樹木而錯過森林,所以我認為分享此解決方案以了解其他人的想法可能是個好主意。
翻譯自: https://www.javacodegeeks.com/2013/04/running-junit-tests-repeatedly-without-loops.html
junit 循環測試
總結
以上是生活随笔為你收集整理的junit 循环测试_重复运行JUnit测试而没有循环的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 180个非常有用的电脑知识
- 下一篇: 计算机组织与结构【9 高速缓冲存储器(C