簡體   English   中英

如何使用不同的單元測試方法加載不同的資源?

[英]How to load a different resource with different unit test methods?

我大約有15個JUnit測試用例,每個用例都需要一個差異資源文件,從該文件中讀取必要的輸入數據。 當前,我正在每種測試案例方法中對特定的資源文件路徑進行硬編碼。

@Test
public void testCase1() {
    URL url = this.getClass().getResource("/resource1.txt");
        // more code here
}

@Test
public void testCase2() {
    URL url = this.getClass().getResource("/resource2.txt");
        // more code here
}

可能是我可以將所有這些文件都通過setUp()方法加載到單獨的URL變量中,然后在每個測試方法中使用特定的URL變量。 有沒有更好的方法可以做到這一點?

您可以使用TestName規則。

@Rule public TestName testName = new TestName();
public URL url;

@Before
public void setup() {
    String resourceName = testName.getMethodName().substring(4).toLowerCase();
    url = getClass().getResource("/" + resourceName + ".txt");
}

@Test
public void testResource1() {
    // snip
}

@Test
public void testResource2() {
    // snip
}

試試JUnit RunWith(Parameterized.class)

示例,它帶有一個資源名稱和一個int預期結果:

@RunWith(Parameterized.class)

public class MyTest {

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
            {"resource1.txt", 0000}, {"resource2.txt", 9999}
        });
    }

    public final URL url;
    public final int expected;

    public MyTest(String resource, int expected) {
        this.url=URL url = this.getClass().getResource("/"+resource)
        this.expected = expected;
    }

    @Before
    public void setUp() {
    }

    @Test
    public void testReadResource() throws Exception {
        // more code here, based on URL and expected
    }

}

此處的更多信息: http : //junit.org/apidocs/org/junit/runners/Parameterized.html

暫無
暫無

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

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