java - JUnit 4 : Set up things in a test suite before tests are run (like a test's @BeforeClass method, 仅用于测试套件)

标签 java unit-testing junit functional-programming

我想对( 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/

相关文章:

unit-testing - 重申一下 Spock 的阻塞在哪里?

C# 单元测试资源

java - 用 mockito 模拟构造函数

java - Selenium 等待页面源包含

java - 创建单词对、三元组等以在 Bleu 中进行评估

node.js - 如何编写测试 : Socket. io app 单元测试

android - Espresso - 检查 ListView 中是否存在 TextView

java - 意外的 JUnit 行为

java - apache commons 日志记录是否支持占位符?

c# - 如何从 C# 服务终止 Java 应用程序