2017-03-04 41 views
3

我有其具有以下结构在JUnit

TestClass1 
     - testmethod1() 
     - testmethod2() 
     - testmethod3() 
     - testmethod4() 
TestClass2 
      - testmethod11() 
      - testmethod22() 
      - testmethod33() 
      - testmethod44() 

在上述结构I中要执行的testmethod4()作为最终一个测试套件的测试套件执行顺序。即)最后执行。 有一个注释@FixMethodOrder,它执行一个方法,而不是测试类。是否有任何机制来维护测试课堂和测试方法的秩序?使用@FixMethodOrder,我可以通过重命名测试方法的名称来执行该方法,但我无法指示junit执行测试类作为最后一个(最后一个)。

+7

你不应该在意测试顺序。如果它很重要,那么测试之间就存在着相互依存关系,所以你正在测试行为+相互依赖关系,而不仅仅是行为。以任何顺序执行时,您的测试应以相同的方式工作。 –

+0

我的场景是特定的方法正在访问更新db中的值。在此之前,我需要执行所有的测试。我同意你的观点,但你能否告诉我是否还有其他可能性? – Shriram

+0

@Shriram如果我没有得到你的错误。您需要在所有其他测试类之后执行'TestClass1',然后确保最后执行'testmethod4'来执行? – nullpointer

回答

4

虽然再次引用@Andy -

你不应该在乎的测试顺序。如果它很重要,那么测试之间就会产生相互依赖关系,因此您正在测试行为+ 相互依赖性,而不仅仅是行为。以任何顺序执行时,您的测试应以相同的方式运行 。

但如果需要的话的话,你可以尝试Suite

@RunWith(Suite.class) 

@Suite.SuiteClasses({ 
     TestClass2.class, 
     TestClass1.class 
}) 
public class JunitSuiteTest { 
} 

在那里你可以指定

@FixMethodOrder(MethodSorters.NAME_ASCENDING) 
public class TestClass1 { 

    @AfterClass 
    public void testMethod4() { 

,然后小心命名方法testMethod4这样在最后执行,或者您也可以使用@AfterClass,在Junit5中很快可以用@AfterAll代替。

做看看Controlling the Order of the JUnit test by Alan Harder

+0

非常好。 – Shriram

+0

@Shriram欢迎:) – nullpointer

0

@shiriam@Andy Turner已经指出的那样,在运行测试时,你的测试顺序不应该进来的问题。

如果您在执行任何测试之前想要执行的例程,可以在其中一个类中使用静态代码块。

想的东西是这样的:

class TestBootstrap { 
    // singleton instance 
    private static final instance; 
    private boolean initialized; 

    private TestBootstrap(){ 
     this.initialized = false;  
    } 

    public static TestBootstrap getInstance(){ 
     if (instance == null){ 
      instance = new TestBootstrap() 
     } 

    } 
    public void init(){ 
     // make the method idempotent 
     if (!initialzed){ 
     // do init stuff 
     initialized = true; 
     } 
    } 

    public boolean isInitialized(){ 
    return initialized; 
    } 

}

然后在测试中使用这样的:

class TestClass1{ 
    @BeforeClass 
    public void setup(){ 
     TestBootstrap.getInstance().init(); 
    } 


    @Test 
    public void testmethod1(){ 
     // assertions 
    } 

    // .... 

} 

class TestClass2{ 
    @BeforeClass 
    public void setup(){ 
     TestBootstrap.getInstance().init(); 
    } 

    @Test 
    public void testmethod11(){ 
     // assertions 
    } 

    // ... 
} 

通过使用单一实例做了设置为测试您确保仅执行一次测试环境的初始化,而与测试类的执行顺序无关。