簡體   English   中英

Junit循環處理預期的異常

[英]Junit handling expected exceptions in a loop

我已經學會了如何在Junit測試中捕獲異常。 但是現在我想遍歷可能導致異常{null, Object.class}參數,當前測試針對第一個循環運行,然后通過並存在,並且不檢查下一個循環參數。

@Rule
public ExpectedException ee;

public ClassTest() {
    this.ee = ExpectedException.none();
}

/**
 * Test of isCompramised method.
 */
@Test
public void testIsCompramised2() {
    System.out.println("isCompramised Exception");
    Class<?>[] c = {null, Object.class};
    for (Class<?> class1 : c) {
        MyClass instance = new MyClass();

        ee.expect(IllegalArgumentException.class);
        boolean result = instance.isCompramised(class1);
        fail("Exception should have been thrown");

    }
}

所以我嘗試了這一點,它完成了for循環,但是所有預期的異常都失敗了,因為我認為Try Catch現在可以竊取該異常。

/**
 * Test of isCompramised method, of class MyClass.
 */
@Test
public void testIsCompramised2() {
    System.out.println("isCompramised Exception");
    Class<?>[] c = {null, Object.class};
    for (Class<?> class1 : c) {
        MyClass instance = new MyClass();
        try{
            ee.expect(IllegalArgumentException.class);
            boolean result = instance.isCompramised(class1);
            fail("Exception should have been thrown");
        } catch (Exception e){
            continue;
        }
    }
}

有什么建議嗎?

這個對嗎?

try{     
    boolean result = instance.isCompramised(class1);
    fail("Exception should have been thrown");
} catch (Exception e){
    AssertTrue(e instanceOf IllegalArgumentException);
    continue;
}

我會喜歡這樣的東西:

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;

import java.util.Arrays;


@RunWith(Parameterized.class)
public class Foo {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Parameter
    public Class<?> input;

    /**
     * Test of isCompramised method, of class MyClass.
     */
    @Test
    public void testIsCompramised() {
        this.expectedException.expect(IllegalArgumentException.class);
        final MyClass instance = new MyClass();
        instance.isCompramised(input);
    }

    @Parameters(name = "test for {0}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][] { {null}, {Object.class} });
    }
}

(或兩種測試方法,一種表示null ,一種表示Object


編輯:一些補充(請參閱注釋)

@Parameters注釋的方法返回一個包含Object[]Iterable 這些Object[]每一個都綁定到一個@Parameter注釋字段(使用@Parameter的值作為索引[默認:0])。 JUnit Parameterized將遍歷@Parameters數據,並為每個數組設置字段值,然后運行該類中的每個測試。

另請參見: Parameterized javadoc

可以在循環中手動捕獲和檢查異常,而不是使用expect 如果放置在循環中,則“此正確”代碼塊應該可以工作。

因為這是搜索時我要添加解決方案的第一個Google結果。

在我的示例中,如果日期在構造函數中獲取了無效的參數,則Datum會引發異常。

為了測試這一點,我想測試構造函數將不會接受無效輸入並拋出異常。

我測試了應該用for循環拒絕的一系列示例案例。

為了測試循環是否在每次迭代中都引發異常,我僅添加了一個布爾變量,該變量在每次迭代中均針對此確切異常在catch中設置為true,如果該變量在迭代結束時為false,則將引發運行時異常。那會讓測試失敗。

我認為這對於以后的團隊成員來說很容易閱讀,而無需任何關於junit測試的豐富知識。 對於初學者來說,它也更容易使用。

package übungen.blatt_01;

import org.junit.Test;

public class DatumTest {

@Test
public void testConstructor() throws Exception {
    for(int jahr = 1801; jahr <2010; jahr++) {
        for(int monat = 1; monat <= 12; monat++) {
            for(int tag = 1; tag <= Datum.getMonatslänge(monat, jahr); tag++) {
                try{
                    new Datum(tag,monat,jahr);
                }
                catch(Exception e){System.out.println(tag+","+monat+","+jahr); e.printStackTrace(); return;}
            }
        }
    }
}

@Test
public void testAllExclusive() {
    boolean failAsExpected = false;
    for(int jahr = 1801; jahr <2010; jahr++) {
        for(int monat = 12+1; monat <= 24; monat++) {
            for(int tag = 32; tag <= 60; tag++) {
                failAsExpected=false;
                try {
                    testConstructorErrors(tag,monat,jahr);
                }catch(DateOutOfRangeException e){
                    failAsExpected=true;
                }
                if(!failAsExpected)
                    throw new RuntimeException("test failed");
            }
        }
        for(int monat = -1; monat >= -24; monat--) {
            for(int tag = -1; tag >= -60; tag--) {
                try {
                    testConstructorErrors(tag,monat,jahr);
                }catch(DateOutOfRangeException e){
                    failAsExpected=true;
                }
                if(!failAsExpected)
                    throw new RuntimeException("test failed");
            }
        }
    }
}

public void testConstructorErrors(int tag, int monat, int jahr) {
    //put additional code here to increase readability of the test loop
    new Datum(tag,monat,jahr);
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM