24 java junit unit-testing functional-programming
我想在(restful)webservice上做一些功能测试.testsuite包含一堆测试用例,每个测试用例在webservice上执行几个HTTP请求.
当然,Web服务必须运行或测试失败.:-)
启动Web服务需要几分钟(它会提升一些重量级数据),因此我希望尽可能少地启动它(至少所有只有来自服务的GET资源可以共享一个的测试用例).
那么在测试运行之前,有没有办法在测试套件中设置炸弹,就像测试用例的@BeforeClass方法一样?
Sle*_*led 25
现在的答案是@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;
}
Run Code Online (Sandbox Code Playgroud)
现在测试类定义:
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 );
}
}
Run Code Online (Sandbox Code Playgroud)
jUnit 不能做这类事情——尽管 TestNG 确实有@BeforeSuite和@AfterSuite注释。通常,您可以让构建系统来完成此操作。在maven中,有“集成前测试”和“集成后测试”阶段。在 ANT 中,您只需将步骤添加到任务中即可。
你的问题几乎是jUnit 4.x 中 Before 和 After Suite 执行挂钩的重复,所以我会看看那里的建议。