This article mainly introduces JUnit, a detailed explanation of Java unit testing. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
Unit testing is writing test code, which should accurately and quickly ensure the correctness of the basic modules of the program.
JUnit is a Java unit testing framework that is installed by default in Eclipse.
JUnit4
JUnit4 identifies test methods through annotations. The main annotations currently supported are:
@BeforeClass will only be executed once globally, and it is the first one to run
@Before in the test method Run before running
@Test test method
@After Allow after test method runs
@AfterClass will only be executed globally once and is the last one to run
@Ignore Ignore this method
The following is based on Eclipse introduction Basic application of JUnit
Basic test
1. Create a new project called JUnitTest. We write a Calculator class, which can be easily implemented Calculator classes for addition, subtraction, multiplication, division, squares, and square roots, and then unit tests these functions.
public class Calculator { private static int result; // 静态变量,用于存储运行结果 public void add(int n) { result = result + n; } public void substract(int n) { result = result - 1; //Bug: 正确的应该是 result =result-n } public void multiply(int n) { } // 此方法尚未写好 public void pide(int n) { result = result / n; } public void square(int n) { result = n * n; } public void squareRoot(int n) { for (; ;) ; //Bug : 死循环 } public void clear() { // 将结果清零 result = 0; } public int getResult(){ return result; } }
1. Introduce the JUnit4 unit test package into this project: right-click on the project and click "Properties", as shown in the figure
In the pop-up properties window, first select "Java Build Path" on the left, then select the "Libraries" tab on the upper right, and then click the "Add Library..." button on the far right, as shown in the figure below Display
Then select JUnit4 in the new pop-up dialog box and click OK , as shown in the picture above, the JUnit4 software package is included in our project.
2. Generate JUnit test framework: Right-click the class in Eclipse's Package Explorer to pop up the menu and select "New JUnit Test Case". As shown in the picture below:
The complete CalculatorTest code is as follows:
public class CalculatorTest { private static Calculator calculator = new Calculator(); @Before public void setUp() throws Exception { calculator.clear(); } @Test public void testAdd() { calculator.add(3); calculator.add(4); assertEquals(7, calculator.getResult()); } @Test public void testSubstract() { calculator.add(8); calculator.substract(3); assertEquals(5, calculator.getResult()); } @Ignore("Multiply() Not yet implemented") @Test public void testMultiply() { fail("Not yet implemented"); } @Test public void testpide() { calculator.add(8); calculator.pide(2); assertEquals(4, calculator.getResult()); } }1. Run the test code: After modifying the above code, we right-click on the CalculatorTest class and select "Run As a JUnit Test" to run our test, as shown in the figure below The running results are as follows: The red color of the progress bar indicates that an error was found. The specific test results are shown above the progress bar, saying "A total of 4 tests were conducted, of which 1 test was ignored and one test failed."
Limited time test
@Test(timeout = 1000) public void squareRoot() { calculator.squareRoot(4); assertEquals(2, calculator.getResult()); }The Timeout parameter indicates the time you want to set. , the unit is milliseconds, so 1000 represents 1 second.
测试异常
JAVA中的异常处理也是一个重点,因此你经常会编写一些需要抛出异常的函数。那么,如果你觉得一个函数应该抛出异常,但是它没抛出,这算不算Bug呢?这当然是Bug,并JUnit也考虑到了这一点,来帮助我们找到这种Bug。例如,我们写的计算器类有除法功能,如果除数是一个0,那么必然要抛出“除0异常”。因此,我们很有必要对这些进行测试。代码如下:
@Test(expected = ArithmeticException.class) public void pideByZero(){ calculator.pide(0); }
如上述代码所示,我们需要使用@Test标注的expected属性,将我们要检验的异常传递给他,这样JUnit框架就能自动帮我们检测是否抛出了我们指定的异常。
参数化测试
我们可能遇到过这样的函数,它的参数有许多特殊值,或者说他的参数分为很多个区域。
例如,测试一下“计算一个数的平方”这个函数,暂且分三类:正数、0、负数。在编写测试的时候,至少要写3个测试,把这3种情况都包含了,这确实是一件很麻烦的事情。测试代码如下:
public class AdvancedTest { private static Calculator calculator = new Calculator(); @Before public void clearCalculator(){ calculator.clear(); } @Test public void square1() { calculator.square(2); assertEquals(4, calculator.getResult()); } @Test public void square2(){ calculator.square(0); assertEquals(0, calculator.getResult()); } @Test public void square3(){ calculator.square(-3); assertEquals(9, calculator.getResult()); } }
为了简化类似的测试,JUnit4提出了“参数化测试”的概念,只写一个测试函数,把这若干种情况作为参数传递进去,一次性的完成测试。代码如下:
@RunWith(Parameterized.class) public class SquareTest{ private static Calculator calculator = new Calculator(); private int param; private int result; @Parameters public static Collection data() { return Arrays.asList(new Object[][]{ {2, 4}, {0, 0}, {-3, 9}, }); } //构造函数,对变量进行初始化 public SquareTest(int param, int result){ this.param = param; this.result = result; } @Test public void square(){ calculator.square(param); assertEquals(result, calculator.getResult()); } }
执行了3次该测试类,依次采用了数据集合中的数据{处理值,预期处理结果},结果如下:
代码分析如下:
为这种测试专门生成一个新的类,而不能与其他测试共用同一个类,此例中我们定义了一个SquareTest类。
为这个类指定一个Runner,而不能使用默认的Runner,@RunWith(Parameterized.class)这条语句就是为这个类指定了一个ParameterizedRunner
定义一个待测试的类,并且定义两个变量,一个用于存放参数,一个用于存放期待的结果。
定义测试数据的集合,也就是上述的data()方法,该方法可以任意命名,但是必须使用@Parameters标注进行修饰。
定义构造函数,其功能就是对先前定义的两个参数进行初始化
The above is the detailed content of Detailed explanation of JUnit in Java unit testing. For more information, please follow other related articles on the PHP Chinese website!