Java "Junit unit testing" study notes

Junit unit testing:

  • Test Category :
    1. Black Box Testing: do not need to write code , to the input value , output value to see if the program can expect.
    2. white-box testing: the need to write code . Specific attention program execution flow.
    Here Insert Picture Description
  • Junit use: white box
    • step:
      1. Define a test class (test)
        is recommended:
        * Test class name: class name Test tested - CalculatorTest
        * Package name: xxx.xxx.xx.test - cn.itcast.test
      2. Define the test: You can run independently
        recommended:
        * method name: test test method names - testAdd ()
        * Return value: void
        * argument list: Empty parameters
      3. Methods to increase@Test
      4. Import junit depend on the environment
public class CalculatorTest {
    /**
     * 初始化方法:
     *  用于资源申请,所有测试方法在执行之前都会先执行该方法
     */
    @Before
    public void init(){
        System.out.println("init...");
    }

    /**
     * 释放资源方法:
     *  在所有测试方法执行完后,都会自动执行该方法
     */
    @After
    public void close(){
        System.out.println("close...");
    }
    /**
     * 测试add方法
     */
     
    @Test
    public void testAdd(){
       // System.out.println("我被执行了");
        //1.创建计算器对象
        System.out.println("testAdd...");
        Calculator c  = new Calculator();
        //2.调用add方法
        int result = c.add(1, 2);
        //System.out.println(result);

        //3.断言  我断言这个结果是3
        Assert.assertEquals(3,result);
    }
    @Test
    public void testSub(){
        //1.创建计算器对象
        Calculator c  = new Calculator();
        int result = c.sub(1, 2);
        System.out.println("testSub....");
        Assert.assertEquals(-1,result);
    }
}
  • The result of determination:
    * Red: Failed
    * Green: Successful
    * Generally, we will use assertions operation to process the results
    *Assert.assertEquals(期望的结果,运算的结果);

  • Added:
    * @Before:
    * modified method will be automatically executed before the test method
    * @After:
    * modified method is automatically executed after test execution method

Published 41 original articles · won praise 1 · views 549

Guess you like

Origin blog.csdn.net/qq_41620020/article/details/105128066