gpt4 book ai didi

java - 在 junit 4 @Beforeclass @Before 和 @After 测试用例 : wrong order of execution

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:23:53 25 4
gpt4 key购买 nike

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

最佳答案

确保将 @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 .

关于java - 在 junit 4 @Beforeclass @Before 和 @After 测试用例 : wrong order of execution,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47988401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com