2016-05-25 141 views
0

我有一個接口定義了一個合同(即一個Repository),但很少有實現。界面中的每個方法都代表一個功能,我想在它的套件測試類中測試每個功能。JUnit套件合同測試

讓我們假設一個UserRepository界面如下:

public interface UserRepository { 

    Set<User> search(String query); 

    Set<User> findBySomethingSpecific(String criteria1, Integer criteria2); 
} 

目前,以確保我運行相同的測試案例,我創建了一個抽象測試類,和我的每一個實現的具有延伸的測試類抽象測試類。

public abstract UserRepositoryTest { 

    private UserRepository userRepository; 

    @Before 
    public void setUp() { 
     userRepository = createUserRepository(); 
    } 

    @Test public void aTestForSearch() { ... } 
    @Test public void anotherTestForSearch() { ... } 

    @Test public void aTestForSomethingSpecific() { ... } 
    @Test public void anotherTestForSomethingSpecific() { ... } 

    protected abstract UserRepository createUserRepository(); 
} 

//------------------------ 

public class UserRepositoryImplementationTest extends UserRepositoryTest { 

    @Override 
    protected UserRepository createUserRepository() { 
     return new UserRepositoryImplementation(); 
    } 
} 

我想找到一種方法來劃分這個抽象測試類爲一組的小測試,因爲測試類將很快變得不堪重負。我查看了測試套件,但我不明白如何通過注入我的不同實現來創建套件測試類。

另一方面,我發現這個question,但我的一些存儲庫在創建時需要一些邏輯(例如,SQL實現的ConnectionPool)。我目前使用反模式ServiceLocator與不同的Context類來處理創建,但這是static。這就是爲什麼我通過實現有了一個測試類的方法,所以我可以創建上下文並在之後注入它。

回答

0

白衣JUnit 4中,您可以創建一套這樣的:

import org.junit.AfterClass; 
import org.junit.BeforeClass; 
import org.junit.runner.RunWith; 
import org.junit.runners.Suite; 

@RunWith(Suite.class) 
@Suite.SuiteClasses({ 
    TestFeatureLogin.class, 
    TestFeatureLogout.class, 
    TestFeatureNavigate.class, 
    TestFeatureUpdate.class 
}) 

/** 
* 
* This suite will execute TestFeatureLogin,TestFeatureLogout,TestFeatureNavigate and TestFeatureUpdate one after the over. 
* 
* @Before, @After and @Test are no possible of executing in this class. 
* @BeforeClas and @AfterClass are allowed only. 
* 
* */ 
public class FeatureTestSuite { 
    // the class remains empty of test,although it is possible set up a before class and after class annotations. 
    // used only as a holder for the above annotations 

    @BeforeClass 
    static public void beforeClass(){ 
     System.out.println(FeatureTestSuite.class.toString() + " BeforeClass Method"); 
    } 

    @AfterClass 
    static public void AfterClass(){ 
     System.out.println(FeatureTestSuite.class.toString() + " AfterClass Method"); 
    } 
} 

完整的例子可以發現here

你必須有考慮的另一件事情是,@Test是沒有一個很好的做法抽象類中的單元測試。如果您想測試您的實現,請創建擴展Abstract類的測試類。

+0

'FeatureTestSuite'如何爲所有套件類注入依賴關係? – MiniW

+0

@MiniW另一種選擇是使用Junit規則http://stackoverflow.com/a/13489506/1371064和JUnit參數。顯然,這取決於你想測試的那種測試。在我的案例中,我總是在其上下文中使用Spring和innject依賴關係。這裏有一個示例如何http://stackoverflow.com/a/14946430/1371064 –