在JUnit中,是否可以为每个测试用例使用不同的@Before和@After?

11

我刚接触Java & JUnit,发现有不同的Fixtures。我在网上搜索了很多,但是没有得到答案。

JUnit中,是否可以为不同的测试用例使用不同的@Before @After?例如:如果我有以下测试用例,那么是否可以为test使用不同的@Before,为test1使用不同的@Before

 import static org.junit.Assert.assertEquals;

 import org.junit.After;
 import org.junit.AfterClass;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Ignore;
 import org.junit.Test;

 public class testJUnit {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    System.out.println("Before Class");
}

@AfterClass
public static void tearDownAfterClass() throws Exception {
    System.out.println("Tear Down After Class");
}

@Before
public void setUp() throws Exception {
    System.out.println("Setup");
}

@After
public void tearDown() throws Exception {
    System.out.println("Tear Down");
}

@Test
public void test() {
    int a = 1;
    assertEquals("Testing...", 1, a);
}

@Ignore
@Test
public void test1() {
    int a = 156;
    assertEquals("Testing...", 156, a);
}

}

有人能指导我吗?


3
如果这些测试用例没有共享相同的初始化/上下文,或许它们不应该在同一个类中。 - LaurentG
@LaurentG 好的,谢谢!顺便问一下,你知道 JUnit 中 main 方法是在哪里调用的吗?我在代码中找不到。它是在 junit 包下完成的吗? - Amrit
JUnit测试没有main。它们直接从开发环境中调用,类似于右键单击类或包并选择“运行测试”,或在菜单中的某个位置;这取决于具体的IDE。您提供的代码足够了,不需要更多的方法。您使用什么:Eclipse、NetBeans等? - Viliam Búr
@ViliamBúr 我正在使用 Eclipse。再次感谢 :) - Amrit
2个回答

12

如果您想要不同的 BeforeAfter,请将每个测试放在其适当的公共类中。

标有 @Before 注解的方法将在执行类中的每个测试之前被执行。


1
你也可以从超类中使用After/Before方法。因此,如果您想要更多的类每个After/Before,只需将它们放入(抽象)超类中。正如名称所示,超级Before将在子类的注释方法之前运行,而超级After将在子类的注释方法之后运行。 - Franz Ebner

7
只需编写一个私有方法,在测试中调用即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接