簡體   English   中英

JUnit 4:在測試運行之前在測試套件中設置東西(比如測試的@BeforeClass方法,僅​​用於測試套件)

[英]JUnit 4: Set up things in a test suite before tests are run (like a test's @BeforeClass method, just for a test suite)

我想在(restful)webservice上做一些功能測試。 testsuite包含一堆測試用例,每個測試用例在webservice上執行幾個HTTP請求。

當然,Web服務必須運行或測試失敗。 :-)

啟動Web服務需要幾分鍾(它會提升一些重量級數據),因此我希望盡可能少地啟動它(至少所有只有來自服務的GET資源可以共享一個的測試用例)。

那么在測試運行之前,有沒有辦法在測試套件中設置炸彈,就像測試用例的@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中,有“預集成測試”和“集成后測試”階段。 在ANT中,您只需添加步驟即可完成任務。

您的問題幾乎是jUnit 4.xBefore和After Suite執行掛鈎的重復 ,因此我將查看那里的建議。

一種選擇是使用像Apache Ant這樣的東西來啟動你的單元測試套件。 然后,您可以在junit目標之前和之后放置目標調用,以啟動和停止Web服務:

<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目標來定義自己的測試)變得更加容易。

順便說一句,讓單元測試實際調用Web服務,數據庫等外部資源是個壞主意。

單元測試應該超級快速運行,並且套件的每次運行延遲“幾分鍾”意味着它將不會運行得盡可能多。

我的建議:

看一下使用EasyMock( http://www.easymock.org/ )之類的單元測試中的模擬外部依賴項。

使用Fitnesse( http://fitnesse.org/ )或自行開發的解決方案構建一個獨立的集成測試套件,該解決方案針對測試環境運行並且持續運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM