测试 断言

JUnit4使用Java5中的注解(annotation),以下是JUnit4常用的几个annotation: 
@Before:初始化方法   对于每一个测试方法都要执行一次(注意与BeforeClass区别,后者是对于所有方法执行一次)
@After:释放资源  对于每一个测试方法都要执行一次(注意与AfterClass区别,后者是对于所有方法执行一次)
@Test:测试方法,在这里可以测试期望异常和超时时间 
@Test(expected=ArithmeticException.class)检查被测方法是否抛出ArithmeticException异常 
@Ignore:忽略的测试方法 
@BeforeClass:针对所有测试,只执行一次,且必须为static void 
@AfterClass:针对所有测试,只执行一次,且必须为static void 
一个JUnit4的单元测试用例执行顺序为: 
@BeforeClass -> @Before -> @Test -> @After -> @AfterClass; 
每一个测试方法的调用顺序为: 

@Before -> @Test -> @After;

 

@Rule // 设置执行最长时间120

@Test有什么作用

@Test有什么作用呢

本来有个方法是这样的
public class JdbcTemplateTest {
public static void main(String[] args) {

但是如果在上面加上@Test后
就变成这样

@Test
public void mainTest() {

有没有发现,没有了public static void main(String[] args) {

这就是@Test的作用,省略了public static void main(String[] args) {,表示测试类的方法

 

@Ignore注解

了解如何使用@Ignore注解。在测试类FirstTest中,我们添加@Ignore注解到test2()方法。以这种方式,我们期望这个测试方法将被忽略,不被执行。

  1. package com.test.junit;
  2. import static org.junit.Assert.*;
  3. import org.junit.Ignore;
  4. import org.junit.Test;
  5. public class FirstTest {
  6. String str1 = "===========测试1===============";
  7. String str2 = "===========测试2===============";
  8. @Test
  9. public void test1() {
  10. System.out.println(str1);
  11. }
  12. @Ignore
  13. @Test
  14. public void test2() {
  15. System.out.println(str2);
  16. }
  17. }

事实上,这输出会发生什么:

===========测试1===============

现在,我们将从test2()方法去除@Ignore注解,修改为注释整个类来代替。
posted @ 2021-02-22 16:58  Ga7l  阅读(98)  评论(0)    收藏  举报