java test-1 JUnit 简介

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Max {

   public int max(int a, int b) {

      if (a > b) {
         return a;
      } else {
         return b;
      }
   }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class Test {

   public static void main(String[] args) {

      Max max = new Max();
      if (2 == max.max(1, 2)) {
         System.out.println("pass");
      } else {
         System.out.println("fail");
      }
   }
}

main()方法测试缺陷

不能把测试代码分离

添加新测试方法,要在main() 添加方法调用

没有打印出测试结果和期望结果,例如,expected: 2, but actual: 1

需要对打印或者输出结果进行人为的判断

……

JUnit

  • 给出成功的测试和失败的测试

  • 测试报告:成功率/代码覆盖率

JUnit 3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
public class XXTest extends TestCase{

   public void setUp() throws Exception {
   }

   public void tearDown() throws Exception {
   }

   public void testAdd() {
   
   }
}

必须继承自TestCase 测试方法必须test开头

对错误的测试,只能通过fail产生一个错误,try里assertTrue(true)来测试

JUnit 4

用 Java5 Annotation 简化测试用例的编写,更灵活与方便

JUnit5

子项目及不同模块组成

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

1

JUnit3或4的兼容性

JUnit Vintage提供TestEngine在JUnit 5平台上运行基于JUnit 3和JUnit 4的测试的实现

生命周期

2

@Annotations

JUnit5 JUnit4
@Test @Test
@TestFactory N/A
@DisplayName N/A
@BeforeEach @Before
@AfterEach @After
@BeforeAll @BeforeClass
@AfterAll @AfterClass
@Nested N/A
@Tag N/A
@Diable @Ignore
@ExtendWith N/A

@Assertions

JUnit5 JUnit4
fail fail
assertTrue assertTrue
assertThat N/A
assertSame assertSame
assertNull assertNull
assertNotSame assertNotSame
assertNotEquals assertNotEquals
assertNotNull assertNotNull
assertFalse assertFalse
assertEquals assertEquals
assertArrayEquals assertArrayEquals
assertAll
assertThrows