2015-12-03 11 views
0

我创建了一个测试套件,用@ClassRule打开连接等。现在我可以运行我所有的测试,连接只打开一次。如何运行单个测试,并仍然访问测试套件中定义的资源?

但是现在,当我尝试运行单个测试时,出现错误,因为连接未打开。我该如何解决这个问题?这说明了什么,我试图做

代码:

@RunWith(Suite.class) 
@SuiteClasses({MyTestCase.class}) 
public class MyTestSuite { 

    public static String connection = null; 

    @ClassRule 
    public static ExternalResource resource = new ExternalResource() { 

     @Override 
     protected void before() throws Throwable { 
      connection = "connection initialized"; 
     }; 

     @Override 
     protected void after() { 
      connection = null; 
     }; 
    }; 
} 

public class MyTestCase { 

    @Test 
    public void test() { 
     Assert.notNull(MyTestSuite.connection); 
    } 
} 

编辑:后@Jens Schauder不建议当前的解决方案。工程,但看起来很丑。有没有更好的办法?

public class ConnectionRule extends ExternalResource { 

    private static ConnectionRule singleton = null; 
    private static int counter = 0; 

    private String connection = null; 

    public static ConnectionRule newInstance(){ 
     if(singleton == null) { 
      singleton = new ConnectionRule(); 
     } 
     return singleton; 
    } 

    @Override 
    protected void before() throws Throwable { 
     if(counter == 0){ 
      System.out.println("init start"); 
      connection = "connection initialized"; 

     } 
     counter++; 
    }; 

    @Override 
    protected void after() { 
     counter--; 
     if(counter == 0){ 
      System.out.println("init end"); 
      connection = null; 
     } 
    }; 

    public String getConnection() { 
     return connection; 
    }  
} 

@RunWith(Suite.class) 
@SuiteClasses({MyTestCase.class, MyTestCase2.class}) 
public class MyTestSuite { 

    @ClassRule 
    public static ConnectionRule rule = ConnectionRule.newInstance(); 
} 

public class MyTestCase { 

    @ClassRule 
    public static ConnectionRule rule = MyTestSuite.rule; 

    @Test 
    public void test() { 
     Assert.notNull(rule.getConnection()); 
    } 
} 

MyTestCase2是相同的。

回答

1

将规则放在测试上,而不是TestSuite。

你可能会延长规则,以便:

  • 它不会重新连接,如果它已经存在

  • 保持对连接的引用,所以连接可以通过后得到重用试验。

  • 对两个测试之间的连接的引用可能是soft or weak one

+0

我将有多个测试案例,我想避免复制/粘贴规则,每个... – bigGuy

+0

你你复制的唯一的事情是一样的东西@ClassRule ConnectionRule规则= ConnectionRule.instance( );不应该坏。你甚至可以在超类中提取它,但我不建议这样做。 –

+0

按照您的建议实施它(请参阅编辑)。现在的问题是,由于我在多个测试用例中有类规则,因此连接会多次打开/关闭。 – bigGuy

相关问题