【问题标题】:Is it possible to use different @Before @After for each test case in JUnit?是否可以为 JUnit 中的每个测试用例使用不同的 @Before @After ?
【发布时间】:2023-03-04 01:46:02
【问题描述】:

我是Java & JUnit 的新手,遇到了不同的Fixtures。我在网上搜索了很多,但没有得到答案。

JUnit中的不同测试用例是否可以使用不同的@Before @After? 例如:我有以下 TC 那么是否可以使用不同的@Before 进行测试和不同的@Before 进行测试1

 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);
}

}

谁能指导我?

【问题讨论】:

  • 如果你的测试不共享相同的初始化/上下文,也许它们不应该在同一个类中......
  • @LaurentG 好的。谢谢!顺便说一句,你知道在哪里为 JUnit 调用了 main,因为我在它的代码中找不到。是在junit包下做的吗?
  • JUnit 测试没有main。它们是直接从开发环境中调用的——比如右键单击一个类或包并选择“运行测试”,或者在菜单中的某个位置;取决于特定的IDE。你提供的代码就够了,不需要更多的方法。您使用什么:Eclipse、NetBeans、...?
  • @ViliamBúr 我正在使用 Eclipse。再次感谢:)

标签: java eclipse unit-testing junit


【解决方案1】:

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

用@Before 标记的方法将在执行之前执行 课堂上的每一个测试。

【讨论】:

  • 您也可以使用超类中的 After/Before 方法。因此,如果您想要每个 After/Before 更多的类,只需将它们放入(抽象)超类中。顾名思义,super Before 将在您的子类的注释方法之后运行,super After 将在您的子类的注释方法之后运行。
【解决方案2】:

只需编写一个您在测试中调用的私有方法。

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多