在junit 4 @Beforeclass @Before和@After测试案例:错误的执行顺序

时间:2017-12-27 07:55:31

标签: java junit4

我正在尝试使用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

1 个答案:

答案 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