【问题标题】:Execute setup() once workaround causing TestSuit to fail执行 setup() 一次解决方法导致 TestSuit 失败
【发布时间】:2011-03-31 07:17:56
【问题描述】:

我有 2 个文件:

xxxxxTest.java [refer this]

public class xxxxxTest extends TestCase {

    // Run setup only once
    public static Test suite() {
        TestSetup setup = new TestSetup(new TestSuite(xxxxxTest.class)) {
            protected void setUp() throws Exception {
              //Some init which i need only once
            }

            protected void tearDown() throws Exception {

            }
        };
        return setup;
    }

    public void testMyFirstMethodTest() {
        assertNotNull(do stuff here);
    }
}

AllTests.java

public class AllTests {
    public static Test suite() {
        TestSuite suite = new TestSuite("Test for xxxxxx");
        //$JUnit-BEGIN$
        suite.addTestSuite(xxxxxTest.class);
        //$JUnit-END$
        return suite;
    }
}

所以,我的个人测试(xxxxxTest.java)工作正常,完全符合我的要求。当我运行我的测试套件(AllTests.java)时,它失败了,因为我在 xxxxxTest.java 中提供的 setup() 中的 init 是没有被执行。

有什么建议吗?

更新

我在 JUnit 4 中尝试了@BeforeClass。但是,它没有帮助,因为在我的 ssetUp() 方法中,我启动了一个嵌入式 Jetty 服务器 (server.start()),该服务器与我发布的代码一起工作正常,但是当我对@BeforeClass 做同样的事情时,它就不起作用了。

【问题讨论】:

    标签: unit-testing junit installation test-suite


    【解决方案1】:

    在极少数情况下,我在使用 JUnit3 时也会使用 static。

    在你的情况下:

    • 试一试static{} initializer,它可能与静态初始化相反。
    • 如果可能,升级到 JUnit4 并使用 @BeforeClass 注释(它为测试类运行一次)。您的其他 JUnit3 测试类也应该可以使用 JUnit4 测试运行器运行。

    【讨论】:

      【解决方案2】:

      类似于 manuel 的观点:您需要使用 JUnit 3 吗?那么类级静态初始化程序可能是您的最佳选择。

      否则,我建议使用 JUnit 4,它有一个可能会喜欢的构造:

      import org.junit.Assert;
      import org.junit.BeforeClass;
      import org.junit.Test;
      
      
      public class xxxxxTest  {
      
          @BeforeClass
          public static void beforeClass() {
              //Some init which i need only once
          }
      
          @Test
          public void testMyFirstMethodTest() {
              Assert.assertNotNull("");//do stuff here);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-05
        • 1970-01-01
        • 1970-01-01
        • 2011-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多