4. Using JUnit test in Eclipse to ensure that software development quality has a very important role, unit test is essential, Junit is a very powerful unit test package, which can be single / multiple methods for one / multiple classes Test, you can also combine different TestCase into TestSuit to automate test tasks. Eclipse is also integrated with JUnit, which can be easily written in TestCase. We created a Java project, add an Example.Hello class, first we add an ABS () method to the Hello class, the role is to return absolute values: Next, we are ready to test this method to ensure normal function. Select Hello.java, right click, select New-> JUnit Test Case: Eclipse will ask if you add a junit.jar package, then create a new Hellotest class after you are used to test the Hello class. Select Setup () and Teardown (), then click "Next": Select the method you want to test, we select the ABS (int) method, entered in Hellotest.java) after completion: Junit will perform tests in the following order: (rough code )
TRY {Hellotest Test = New Hellotest (); // Establish test class instance test.setup (); // Initialization test environment test.testabs (); // Test a method Test.teardown (); // Clean resources} Catch ...
Setup () is an instance of a Hello class; Teardown () is used to clean the resources, such as released files, and more. The method starting with TEST is considered to be a test method, and JUnit will execute the TestXxxxx () method in turn. In the Testabs () method, we select positive, negative numbers, and 0 for the test of ABS (). If the method return value is the same as the expected result, Assertequals does not produce an exception. If there are multiple TestXxxx methods, Junit creates multiple XXXTEST instances, running a Testxxxx method each time, setup () and Teardown () will be called before and after Testxxx, so don't depend on Testb () in a Testa (). You can see the JUnit test results: Green indicate test, as long as one test is not passed, it will display the method of not passing the test. You can try to change the code of the ABS (), deliberately returning the result of the error (such as Return n 1;), then run the junit will report an error. If there is no junit panel, select Window-> show view-> Other, open JUnit's View: JUnit is tested by unit testing, you can find many bugs in the development phase, and multiple Test Case can be combined into test suite, let the whole test Automatic completion, especially suitable for XP methods. Each time a small new function is added or a small modification is made to the code, it is immediately running a Test Suite, ensuring that the new and modified code does not destroy the original features, greatly enhance the maintenanceability of the software, and avoid code gradually. " rot".