This is not the first time I have heard of unit testing, but I have just heard that I have never used it. How to test a module? Do I have to write a test program specifically for a unit and then use the test unit code to test? I thought so. After learning the spring framework, I realized what unit testing is all about.
The first instance injected by set in the previous article is the test object. Perform unit testing.
1, copy the jar package
junit-3.8.2.jar (4.x mainly adds annotation applications)
2, write business class
public class User{ privateString username; publicString getUsername() { returnusername; } publicvoid setUsername(String username) { this.username= username; } //添加方法 publicString login() throws Exception{ if("admin".equals(username){ return"success"; }else{ return"error"; } } }
3, Define the test class
It is best to create a separate project for the test class, or define a separate folder for storage. You need to inherit junit.framework.TestCase
4 and add a test method
The test method must be public , there should be no return value. The method name must start with test and have no parameters.
The test method has an order of execution, according to the order of the method definition.
Multiple test methods test the same business method. Generally, each Every logical branch structure has been tested.
public class TestUserextends TestCase{ publicvoid testUser_Success() throws Exception{ //准备数据 Useraction = new User(); action.setUsername("admin"); //调用被测试方法 Stringresult = action.login(); //判断测试是否通过 assertEquals("success",result); } }
Run the program. If the test is successful, the result as shown below will appear.
If the operation fails and there is a method that fails the test, it will be displayed. Which method is wrong? The green bar in the image above will turn red.
5, the life cycle method of the test class
//用来进行初始化操作 @Override protectedvoid setUp() throws Exception { System.out.println("setUp..."); } //用来做销毁操作 @Override protectedvoid tearDown() throws Exception { System.out.println("tearDown..."); }
setUp method will be executed once before each test method. The tearDown method will be executed once after each test method
The above is the content of spring framework learning (3) junit unit test. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!