4. Use JUnit in eclipse
Testing plays an important role in ensuring the quality of software development, and unit testing is essential. JUnit is a very powerful unit testing package, you can test one or more methods of one or more classes, and combine different testcase into testsuit to automate the test tasks. Eclipse also integrates JUnit, which makes it easy to compile testcase.
We create a Java project and add an example. Hello class. First, we add an ABS () method to the Hello class to return the absolute value:
Next, we are going to test this method to ensure its functionality is normal. Select hello. Java, right-click, and choose new-> JUnit test case:
Eclipse will ask whether to add the JUnit. jar package and create a hellotest class to test the Hello class.
Select setup () and teardown (), and then click "Next ":
Select the method to be tested. We select the ABS (INT) method and enter the following in hellotest. Java:
JUnit performs the test in the following order: (rough code)
Hellotest test = new hellotest (); // create a test instance
Test. Setup (); // initialize the test environment
Test.Testabs(); // Test A Method
Test. teardown (); // clear Resources
Setup () is to create a test environment. Here we create a hello class instance; teardown () is used to clear resources, such as releasing open files. Methods Starting with test are considered as test methods. JUnit will execute the testxxx () method in sequence. In the testabs () method, we select positive, negative, and 0 for the ABS () test. If the return value of the method is the same as the expected result, assertequals will not generate an exception.
If there are multiple testxxx methods, JUnit will create multiple xxxtest instances. Each time a testxxx method is run, setup () and teardown () will be called before and after testxxx. Therefore, do not depend on testb () in a testa ().
Run-> Run as-> JUnit test directly to view the JUnit test results:
Green indicates that the test is successful. If one test fails, the red color is displayed and the method for failing the test is listed. Attackers can try to change the ABS () Code and intentionally return incorrect results (for exampleReturn n + 1), And then run JUnit to report errors.
If the JUnit panel is not available, choose Window> show View> other to open the view of JUnit:
Through unit tests, JUnit can identify many bugs in the development phase. In addition, multiple test cases can be combined into test suite to automatically complete the test, which is especially suitable for the XP method. Each time you add a small new function or make minor changes to the Code, you can immediately run test suite to ensure that the newly added and modified code does not destroy the original function, this greatly enhances Software maintainability and avoids code corruption ".