2013-10-23 23 views
5

我是Java & JUnit的新手,碰到不同的赛程。我在网上搜索了很多,但我无法得到答案。是否可以在JUnit中为每个测试用例使用不同的@Before @After?

是否有可能在JUnit中针对不同的测试用例使用不同的@Before @After? 对于例如:我有以下的TC则有可能要用于测试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); 
} 

} 

测试&不同@Before不同@Before任何人都可以指导我?

+3

也许你的测试不应该在同一个类,如果他们不共享相同的初始化/上下文... – LaurentG

+0

@LaurentG行。谢谢!顺便说一句,你知道'main'为JUnit调用的地方,因为我无法在其中找到代码。它是在junit包下完成的吗? – Amrit

+0

JUnit测试没有'main'。它们直接从开发环境中调用 - 就像右键单击一个类或包并选择“运行测试”或菜单中的某处;取决于具体的IDE。你提供的代码是足够的,它不需要更多的方法。你用什么:Eclipse,NetBeans,...? –

回答

6

如果你想不同的BeforeAfter,把每个测试在其适当的公共类标有@Before执行 在每类测试之前将被执行

方法。

+1

谢谢!理解:) – Amrit

+1

您也可以使用超类的After/Before方法。 所以如果你想要更多的类每个后/之前把它们放入一个(抽象)超类。正如名称所示,超级之前将运行之前,超级之后的子类的注释方法。 –

3

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

相关问题