[英]What is the logic of @Rule(JUnit) declaration and assignment in a Groovy class
嘗試在常規文件中創建規則的一些變體,我想到了@Rule不是描述DECLARATION,而是描述ASSIGNMENT。 因此,跑步者在加載測試時會嘗試所有規則以進行正確分配。
//Correct variants:
@Rule
public ErrorCollector collector1= new ErrorCollector();
public ErrorCollector collector2= null;
@Rule
collector2= new ErrorCollector();
public ErrorCollector collector3;
@Rule
collector3= new ErrorCollector();
// incorrect variants:
@Rule
public ErrorCollector collector4= null;
@Rule
public ErrorCollector collector5;
@Rule
public ErrorCollector collector5=somethingThatIsNotRule;
@Rule
public ErrorCollector collector5=anotherRule;
但是,然后我得出了一些自相矛盾的變體:
//these lines are not only taken by the runner, but also passed without errors:
public ErrorCollector collector6;
{
@Rule
collector6= null;
}
public ErrorCollector collector7=null;
{
@Rule
collector7= null;
}
它的邏輯是什么?
這似乎是Runner中的錯誤-Runner在構建測試之前進行了過多檢查。
在Java中,JUnit運行器檢查@Rule
批注是否應用於返回TestRule或MethodRule的公共非靜態字段或公共非靜態方法。
如果字段或方法上有@Rule
批注,則該值必須為非null值,否則您將在執行測試期間得到NullPointerException。
您的示例比這更復雜,因為Groovy是一種動態語言,因此它在運行時而不是編譯時進行檢查。 我懷疑Collector2和Collector3實際上沒有做任何事情。 @Rule
批注不適用於該字段。
collector4 => NullPointerException
collector5 => same as collector5
collector5a => when you execute, I suspect Groovy doesn't find the
expected methods on your somethingThatIsNotRule, or
you're getting a ClassCastException or something similar.
collector5b => same as 5b for anotherRule
同樣,對於您的悖論, @Rule
批注實際上並未應用於該字段。
我懷疑您的困惑是由於Groovy沒有抱怨@Rule
在不是字段或方法的東西上的使用(而Java會這樣)。 它可能不會抱怨,但是JUnit會忽略這樣的注釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.