9

我希望从 Java 测试中启动 GUI 应用程序 2 次。在这种情况下我们应该如何使用@annotation

public class Toto { 

    @BeforeClass 
    public static void setupOnce() { 
        final Thread thread = new Thread() {
            public void run() {
               //launch appli
            }
        }; 
        try { 
            thread.start(); 
        } catch (Exception ex) { } 
    }
} 
public class Test extends toto {
    @Test 
    public void test() {
        setuptonce(); 
        closeAppli(); 
    } 

    @test 
    public void test2() 
    {
        setuptonce(); 
    } 
}

要再次启动它,我应该使用哪个注释?@afterclass?

4

2 回答 2

22

带有注释的@BeforeClass方法意味着它在测试类中运行任何测试方法之前运行一次。带有注释的@Before方法在类中的每个测试方法之前运行一次。这些的对应物是@AfterClass@After

可能您的目标是以下内容。

@BeforeClass
public static void setUpClass() {
  // Initialize stuff once for ALL tests (run once)
}

@Before
public void setUp() {
  // Initialize stuff before every test (this is run twice in this example)
}

@Test
public void test1() { /* Do assertions etc. */ }

@Test
public void test2() { /* Do assertions etc. */ }

@AfterClass
public static void tearDownClass() {
  // Do something after ALL tests have been run (run once)
}

@After
public void tearDown() {
  // Do something after each test (run twice in this example)
}

您不需要@BeforeClass在测试方法中显式调用该方法,JUnit 会为您做到这一点。

于 2010-03-18T21:57:02.903 回答
0

@BeforeClass 注释用于在测试实际运行之前运行一次。

因此,根据您想要获得什么(以及为什么),您可以简单地将启动代码包装在一个循环中,将启动代码移动到其他方法中并从其他地方调用它或编写单独的测试用例。

于 2010-03-18T20:51:47.327 回答