Junit unit testing
Article Directory
1. Use steps
(1) Create a test class:
Naming suggestions:
① Class name: the name of the tested class Test
② Package name: xxx.xxx.test
(2) Create a test method:
Naming suggestions:
① Method name: test method name
② Return value: void
③ Parameter list: empty parameter
(3) Write before the test method (on the previous line)@Test
(4) Import Junit dependent environment:
method one:
Way two:
The final steps of the above two methods:
2. Judgment results
(1) After running the test method, the console prompts that the color is green to indicate error, and the console is red to indicate error
(2) Generally, the static method in Assert is used to compare whether the expected result of the test method after running is consistent with the final result:
3. Execution sequence of test methods
(1) @Before
The modified method will be automatically executed before the test method is executed, and is often used for resource applications
(2) @After
The modified method will be automatically executed after the test method is executed, often used for the release of resources
4. Examples
public class Calculator {
//加法
public int add(int a, int b) {
return a + b;
}
}
import com.qizegao.junit.Calculator;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class CalculatorTest {
@Test
public void testAdd() {
System.out.println("testAdd执行了!");
Calculator calculator = new Calculator();
int res = calculator.add(1, 2);
//第一个参数值是预期结果,第二个参数是实际结果
Assert.assertEquals(3, res);
}
@Before
public void init() {
System.out.println("init执行了!");
}
@After
public void close() {
System.out.println("close执行了!");
}
}
The location of the above two classes:
operation result:
Change the expected result to the running result of 1: