簡體   English   中英

為什么我的DataPoints方法被多次調用?

[英]Why is my DataPoints method being called multiple times?

這個測試班:

@RunWith(Theories.class)
public class TheoriesConfusion
{

    @DataPoints
    public static int[] ints()
    {
        System.out.println("Generator called");
        return new int[]{1, 2, 3, 4, 5};
    }

    @Theory
    public void twoArgTest(int x, int y)
    {
        assertTrue(x < y || x >= y);
    }
}

打印以下輸出:

Generator called
Generator called
Generator called
Generator called
Generator called
Generator called
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.137 sec

這是非常違反直覺的,因為我希望數據生成函數僅被調用一次。 這在創建隨機數據時或在每次調用數據返回方法返回不同結果的任何情況下都具有含義,因此,我想了解一下。

經過一些實驗,我發現使用c args對一個長度為n的數組進行了測試,其generate函數被稱為x次,其中x = n^c + n^(c-1) + ... + n^0

源代碼有點難以理解,但是我的假設是它的工作原理如下(偽代碼):

for firstArg in generateArgs():
    for secondArg in generateArgs():
        for thirdArg in generateArgs():
            testTheory(firstArg, secondArg, thirdArg)

這是有道理的,基本上它只是不緩存方法的結果,因此,如果您希望方法僅被調用一次,則必須注釋一個靜態字段,例如:

@DataPoints
public static int[] ints = ints();

public static int[] ints()
{
    System.out.println("Generator called");
    return new int[]{1, 2, 3, 4, 5};
}

暫無
暫無

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

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