JUnit unit test (2) -- JUnit Basics
1. Basic Introduction
1. JUnit is a framework for testing code. The purpose of testing is to ensure that the Code is correct, rather than the code is correct.
2. The test class should not be put together with the target class, but the compiled class file should be put together to ensure that the product code is separated from the test code without affecting each other.
3. unit testing is mainly used to test whether the program results are equal to the expected values.
2. The JUnit testing framework is generally divided into two types (JUnit 3.8 and JUnit 4.x)
2.1. JUnit 3.8
The package involved is generally import junit. framework .*
In JUnit 3.8, the test class inherits the TestCast class, And the TestCast class inherits the Assert class. The test method must meet the following principles:
1) modifier set to public
2) return type void
3) No method parameter
4) The method name must start with test.
5) test classes all inherit from TestCase classes
In addition, the test class cannot depend on the execution sequence of the test method.
In the new test class, there are two methods that need to be emphasized:
SetUp method and testDown method: both are methods of the TestCase class.
1) The setUp method is executed before each test method is executed. You can perform initialization, for example, class instance declaration.
2) The testDown method is executed after each test method is executed. For example, the object is destroyed here.
2.2. JUnit 4
The involved package is import org. junit .*
In junit 4, the test class does not need to inherit from the TestCase class, and the name of the test method does not need to start with test, which is mainly defined by annotation, you only need to add @ Test to the test method, but some principles will still be designed in the junit3 style. For example, the Test method starts with test and gets used to the problem,
• @ Test: A flag defining a Test method
• @ Test (timeout = 1000): sets the timeout time. If the Test time exceeds the defined timeout, the Test fails.
• @ Test (expected): Declares exceptions, for example, @ Test (expected = Exception. class)
• @ Before: the same effect as the setUp () method on junit 3.8. The method name should be the same as setUp (), but not necessarily executed Before each test method.
• @ After: Same effect as the tearDown () method on junit 3.8, the method name should be the same as tearDown (), but cannot be forced to execute After each test method
• @ BeforeClass: The method affirmed by this annotation. The function is to execute all the test methods only once.
• @ AfterClass: The method affirmed by this annotation. The function is to execute all the test methods only once.
• @ Ignore: Disable the test method or test class from being executed and disable the test function.