beforeTestMethod 方法在類中的任何測試方法執行之前執行。
afterTestMethod 方法在類中的每個測試方法執行之后執行。
圖 2 進一步描述了測試類的生命周期。


清單 5 演示了配置方法的一些示例。請注意,如果您使用組,那么配置方法也必須屬于某個組。而且,配置方法的四種類型彼此之間不是互斥的,所以可以把方法定義成同時屬于一種或多種配置方法類型。(作為例子,請參閱清單 5 中的 aroundTestMethods() 方法)。

@Configuration(beforeTestClass = true, groups = {"tests.workflow"})public void setUp(){ System.out.println("Initializing...");}@Configuration(afterTestMethod = true, beforeTestMethod = true, groups = {"tests.workflow"})public void aroundTestMethods(){ System.out.println("Around Test");} |
TestNG 中的配置方法是 JUnit 的 setUp() 和 tearDown() 方法的增強版;它們的主要目的是為測試創建正確的執行上下文,并在測試用例執行之后刷新數據。

使用 TestNG,您可以非常簡單、非常容易地檢測異常的發生。很明顯,用 JUnit 也可以做這件事,但是正如您在清單 6 中的示例中所看到的,使用 TestNG 的 @ExpectedExceptions 標注可以使代碼編寫驚人地容易和簡單。 @ExpectedExceptions 標注指明框架能夠容忍拋出的 NumberFormatException 異常,所以不應當被當作是故障。要查看在某行代碼中是否拋出異常,您可以直接在這行代碼之后加入 assert false 語句。這意味著 只有 在指定行中拋出特定類型的異常的時候,您才會通過測試。

public class NumberUtilsTest{ @Test(groups = {"tests.math"}) @ExpectedExceptions(NumberFormatException.class) public void test() { NumberUtils.createDouble("12.23.45"); assert false; //shouldn't be invoked }} |
文章來源于領測軟件測試網 http://www.kjueaiud.com/