作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我想对( Restful )网络服务进行一些功能测试。测试套件包含一堆测试用例,每个测试用例在 web 服务上执行几个 HTTP 请求。
当然,Web 服务必须运行,否则测试将失败。 :-)
启动 web 服务需要几分钟(它会处理一些繁重的数据),所以我想尽可能不频繁地启动它(至少所有测试用例只能从服务中获取资源可以共享一个)。
那么有没有办法在测试套件中设置炸弹,然后像在测试用例的 @BeforeClass 方法中那样运行测试?
最佳答案
现在的答案是在您的套件中创建一个 @ClassRule
。该规则将在每个测试类运行之前或之后(取决于您如何实现)被调用。您可以扩展/实现一些不同的基类。类规则的好处在于,如果您不将它们实现为匿名类,那么您可以重用代码!
这是一篇关于它们的文章:http://java.dzone.com/articles/junit-49-class-and-suite-level-rules
这里有一些示例代码来说明它们的使用。是的,这是微不足道的,但它应该足以说明生命周期,以便您开始。
首先是套件定义:
import org.junit.*;
import org.junit.rules.ExternalResource;
import org.junit.runners.Suite;
import org.junit.runner.RunWith;
@RunWith( Suite.class )
@Suite.SuiteClasses( {
RuleTest.class,
} )
public class RuleSuite{
private static int bCount = 0;
private static int aCount = 0;
@ClassRule
public static ExternalResource testRule = new ExternalResource(){
@Override
protected void before() throws Throwable{
System.err.println( "before test class: " + ++bCount );
sss = "asdf";
};
@Override
protected void after(){
System.err.println( "after test class: " + ++aCount );
};
};
public static String sss;
}
现在是测试类定义:
import static org.junit.Assert.*;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
public class RuleTest {
@Test
public void asdf1(){
assertNotNull( "A value should've been set by a rule.", RuleSuite.sss );
}
@Test
public void asdf2(){
assertEquals( "This value should be set by the rule.", "asdf", RuleSuite.sss );
}
}
关于java - JUnit 4 : Set up things in a test suite before tests are run (like a test's @BeforeClass method, 仅用于测试套件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/349842/
我是一名优秀的程序员,十分优秀!