2017-10-25 11 views
1

例外を除いて特定のメソッドが一連の文字列を処理できることをテストしたいと思います。したがって、私はAssertJのsoft assertionsを使用したい、何かのように:残念ながらこのメソッドがAssertJ 1.xのソフトアサーションで例外をスローしないことをアサートします。

SoftAssertion softly = new SoftAssertion(); 

for (String s : strings) { 
    Foo foo = new Foo(); 

    try { 
     foo.bar(s); 
     // Mark soft assertion passed. 
    } catch (IOException e) { 
     // Mark soft assertion failed. 
    } 
} 

softly.assertAll(); 

、私はJava 6のそれぞれAssertJ 1.xのに固執する必要があるので、私はこれを利用することはできません。

assertThatCode(() -> { 
    // code that should throw an exception 
    ... 
}).doesNotThrowAnyException(); 

AssertJ(またはJUnit)でこれを行う方法はありますか?

答えて

4

テストコードにループを入れるのは良い方法ではないと思います。

テスト内で実行するコードが例外をスローすると、テストに失敗します。 私はJUnit(ライブラリに同梱)にParameterizedランナーを使用することを提案します。公式のJUnit 4のドキュメントから

例:あなたは、私が投票まで意志の代わりにリンクを例を投稿する場合

import static org.junit.Assert.assertEquals; 
import java.util.Arrays; 
import java.util.Collection; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.junit.runners.Parameterized; 
import org.junit.runners.Parameterized.Parameters; 

@RunWith(Parameterized.class) 
public class FibonacciTest { 
    @Parameters 
    public static Collection<Object[]> data() { 
     return Arrays.asList(new Object[][] {  
       { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } 
      }); 
    } 

    private int fInput; 

    private int fExpected; 

    public FibonacciTest(int input, int expected) { 
     fInput= input; 
     fExpected= expected; 
    } 

    @Test 
    public void test() { 
     // Basically any code can be executed here 
     assertEquals(fExpected, Fibonacci.compute(fInput)); 
    } 
} 

public class Fibonacci { 
    public static int compute(int n) { 
     int result = 0; 

     if (n <= 1) { 
      result = n; 
     } else { 
      result = compute(n - 1) + compute(n - 2); 
     } 

     return result; 
    } 
} 
+0

、答えは良いですが、時間上のリンクが解除されますと、さらに読者がすることはできません次に参照してください –

+0

良い点、ありがとう! – Admit

+0

今すぐ完全な答えです、素晴らしい仕事、知識を共有してくれてありがとう –

関連する問題