官术网_书友最值得收藏!

Standard tests in JUnit 3

In JUnit 3, in order to create test cases, we need to extend the class junit.framework.TestCase. This base class includes the framework code that JUnit needs to automatically run the tests. Then, we simply make sure that the method name follows the testXXX() pattern. This naming convention makes it clear to the framework that the method is a unit test and that it can be run automatically.

The test life cycle is controlled in the setup() and tearDown()methods. The TestCase calls setup() before running each of its tests and then calls teardown() when each test is complete. One reason to put more than one test method into the same test case is to share the same test fixture.

Finally, in order to implement the verification stage in the test case, JUnit 3 defines several assert methods in a utility class named junit.framework.Assert. The following table summarizes the main assertions provided by this class:

The following class shows a simple test implemented with JUnit 3.8.2. As we can see, this test case contains two tests. Before each test, the method setUp() will be invoked by the framework, and after the execution of each test, the method tearDown() will be also invoked. This example has been coded so that the first test, named testSuccess() finishes correctly, and the second test named testFailure() ends with an error (the assertion throws an exception):

package io.github.bonigarcia;

import junit.framework.TestCase;

public class TestSimple extends TestCase {

// Phase 1: Setup (for each test)
protected void setUp() throws Exception {
System.out.println("<Setup>");
}

// Test 1: This test is going to succeed
public void testSuccess() {
// Phase 2: Simulation of exercise
int expected = 60;
int real = 60;
System.out.println("** Test 1 **");

// Phase 3: Verify
assertEquals(expected + " should be equals to "
+ real, expected, real);
}

// Test 2: This test is going to fail
public void testFailure() {
// Phase 2: Simulation of exercise
int expected = 60;
int real = 20;
System.out.println("** Test 2 **");

// Phase 3: Verify
assertEquals(expected + " should be equals to "
+ real, expected, real);
}

// Phase 4: Teardown (for each test)
protected void tearDown() throws Exception {
System.out.println("</Ending>");
}

}
All the code examples explained in this book are available on the GitHub repository https://github.com/bonigarcia/mastering-junit5.
主站蜘蛛池模板: 崇明县| 阳山县| 喜德县| 于都县| 泾阳县| 田林县| 河津市| 通城县| 新和县| 夏河县| 绩溪县| 全椒县| 汉川市| 遂溪县| 嘉黎县| 西和县| 吴堡县| 库车县| 平凉市| 乌拉特中旗| 台中市| 伊宁县| 江陵县| 淮南市| 阳谷县| 梁山县| 闻喜县| 晴隆县| 永修县| 杂多县| 栖霞市| 天祝| 榆中县| 富裕县| 遂宁市| 调兵山市| 田阳县| 成安县| 宜都市| 望奎县| 兴安县|