Detail Java unit test Junit framework example

  • 2020-07-21 07:42:48
  • OfStack

Question:

1. Current test problems

2. Junit's attention to detail

3. Junit usage specification

4, assertions

5, case

junit(Unit Testing Framework)

1. Current problems

1. If the current test methods need to be tested, they all need to be called on the main method

2. The current results need our manual comparison

2. Details to Junit's attention

1. When using junit to test a method, the display of green in junit window means that the test is correct; if the display of red means that the test fails due to an exception

2. If you click method name, class name, package name and project name to run junit, test the corresponding method, test method of all classes in the package, and test method of all classes in the project

3. The @ES37en test method cannot be static modified with no visible reference

4, 1 if the test methods need to be ready to test environment or clean up the test environment, you can @ Before, @ After, @ BeforeClass, @ AfterClass the four comments, @ Before, @ After is at the time of each test method test will be called once, @ AfterClass, @ BeforeClass is in all of the test method will be called before and after the test, the method must be static

3. junit usage specification

1. If a class needs to be tested, then the class should correspond to one test class. The naming specification of the test class: the class name of the tested class +Test

2. Generally, 1 test method corresponds to 1 test method. The naming specification of the test method is test+ the method name of the test method

4, assertions

Assertions show the status of the run by comparing the expected and actual values of the run without showing the results.


Assert.assertSame(5, max); //  The bottom layer is used   ==
Assert.assertSame(new String("abc"), "abc");
Assert.assertEquals(new String("abc"), "abc"); // The bottom line is using Equals Methodical comparative 
Assert.assertNull("aa");
Assert.assertTrue(true);

5, case


package cn.xlucas.junit;
import java.io.*;
import org.junit.*;
public class JunitDemo1 {
  // The environment to prepare for testing 
  //@Before
  @BeforeClass
  public static void beforeRead(){
    System.out.println(" Prepare test environment for success ...");
  }
  // Read file data, put the file data all 
  @Test
  public void readFile() throws IOException{
    FileInputStream fileInputStream = new FileInputStream("F:\\a.txt");
    int content = fileInputStream.read();
    System.out.println(" Content: "+content);
  } 
  @Test
  public void sort(){
    System.out.println(" Read file data sort ..");
  }
   // Ways to clean up your test environment 
// @After  
  @AfterClass
  public static void afterRead(){
    System.out.println(" Clean up the test environment ..");
  }
}

I hope you found this article helpful


Related articles: