@Test
方法为只能为 public void 不能私有,不能有返回值,不能为静态方法。
用于测试运行某一方法,加上 static 后方法无法执行,而且 不能有返回值,否则直接报错
java.lang.Exception: Method xxxxxxx() should be void
私有时会报错
java.lang.Exception: Method xxxxxxx() should be public
@Before
方法为只能为 public void 不能私有,不能有返回值,不能为静态方法。
在标有注解 @Test 的方法前执行。
@After
方法为只能为 public void 不能私有,不能有返回值,不能为静态方法。
在标有注解 @Test 的方法后执行。
@BeforeClass
在类中的任意 public static void 方法之前执行,且 必须是 静态方法
不是 static 修饰时报错
java.lang.Exception: Method xxxxxxxx() should be static
不是 public 修饰时报错
java.lang.Exception: Method xxxxxxxx() should be public
同样不能有返回值 否则直接报错
java.lang.Exception: Method xxxxxxx() should be void
方法只能为 public static void
@AfterClass
与 beforeClass 一致。只能是 public static void,不能私有,不能有返回值 必须为静态方法。
在类中的任意public static void方法执行之后执行
案例
最外层即为刚创建的文件 内部只有这几个方法 直接执行@Test 的方法
@Test
public void redisClientTest(){
System.out.println("test-----start----");
System.out.println("test redisClientTest");
System.out.println("test-----end-----");
}
@Before
public void junitBeforeAnnotation(){
System.out.println("before");
System.out.println();
}
@After
public void junitAfterAnnotation(){
System.out.println("after");
System.out.println();
}
@BeforeClass
public static void junitBeforeClassAnnotation(){
System.out.println("beforeClass");
System.out.println();
}
@AfterClass
public static void junitAfterClassAnnotation(){
System.out.println("afterClass");
System.out.println();
}
输出结果
beforeClass
before
test-----start----
test redisClientTest
test-----end-----
after
afterClass
添加一个静态方法且无返回, @Test 中修改如下 其他不变运行
@Test
public void redisClientTest(){
staticMethod();
System.out.println("test-----start----");
System.out.println("test redisClientTest");
System.out.println("test-----end-----");
}
public static void staticMethod(){
System.out.println("staticMethod");
}
输出结果
beforeClass
before
staticMethod
test-----start----
test redisClientTest
test-----end-----
after
afterClass
结论
执行顺序如下
@BeforeClass
@Before
@Test
@After
@AfterClass