English 中文(简体)
JUnit 4:在运行测试之前,在测试套件中设置事物(就像测试套件中的@test s @BeforeClass方法一样)
原标题:
  • 时间:2008-12-08 15:23:00
  •  标签:

我想对(restful)webservice 进行一些功能测试。测试套件包含一堆测试用例,每个测试用例在webservice上执行一些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 );
    }
}

jUnit做不到那样的事情 - 虽然TestNG有 @BeforeSuite @AfterSuite 注释。通常,您需要让构建系统来做这件事。在maven中,有“pre-integration-test”和“post-integration-test”阶段。在ANT中,您只需向任务添加步骤即可。

你的问题几乎就是一个jUnit 4.x中的Before and After Suite 执行挂钩的复制,所以我建议你去那里看一下建议。

One option is to use something like Apache Ant to launch your unit test suite. You can then put a target invocation before and after your junit target to start and stop your webservice:

<target name="start.webservice"><!-- starts the webservice... --></target>
<target name="stop.webservice"><!-- stops the webservice... --></target>
<target name="unit.test"><!-- just runs the tests... --></target>

<target name="run.test.suite" 
        depends="start.webservice, unit.test, stop.webservice"/>

然后,您使用Ant(或您选择的集成工具)运行您的套件。大多数IDE都支持Ant,并且它使得将您的测试移动到持续集成环境中变得更加容易(其中许多使用Ant目标来定义自己的测试)。





相关问题
热门标签