我正在尝试使用Junit 4库运行一些简单的测试,并使用@Before
,@After
和@BeforeClass
注释。但问题是@Before
和@After
正在@BeforeClass
之前执行。这是为什么?
代码:
import junit.runner.Version;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestClass2
{
@BeforeClass
public static void before() throws Exception
{
System.out.println("Before class");
}
@Before
public void setUp() throws Exception
{
System.out.println("Before");
}
@After
public void tearDown() throws Exception
{
System.out.println("After");
}
@Test
public void name() throws Exception
{
System.out.println("Test");
System.out.println("JUnit version is: " + Version.id());
}
}
输出
Before Test JUnit version is: 4.12 After Before class Process finished with exit code 0
答案 0 :(得分:0)
确保将@BeforeClass
方法声明为 static ,并使用JUnit的注释(而不是TestNG)。一个完整的代码例子:
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author sainnr <p/>27.12.2017.
*/
public class TestClass {
@BeforeClass
public static void before() throws Exception {
System.out.println("Before class");
}
@Before
public void setUp() throws Exception {
System.out.println("Before");
}
@After
public void tearDown() throws Exception {
System.out.println("After");
}
@Test
public void name() throws Exception {
System.out.println("Test");
}
}
输出:
Before class
Before
Test
After
根据JUnit文档:http://junit.sourceforge.net/javadoc/org/junit/BeforeClass.html。