2012-09-14 97 views
5

我想第一次用Spring設置Junit測試套件,並嘗試在我的類的幾個變化,但沒有運氣,並以此錯誤結束:「junit.framework.AssertionFailedError:No在MYCLASS」找到測試SpringJUnit4ClassRunner與JUnit測試套件錯誤

簡言之,我有2個測試類都是從相同的基類,它加載Spring上下文如下

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = 
{ 
"classpath:ApplicationContext.xml" 
}) 

我嘗試添加那些2測試類成套件如下

@RunWith(SpringJUnit4ClassRunner.class) 
@SuiteClasses({ OneTest.class, TwoTest.class }) 
public class MyTestSuite extends TestCase { 

//nothing here 
} 

我從螞蟻運行這個測試套件。但是,這給我一個錯誤,說「沒有發現測試」 但是,如果我從螞蟻運行單個2測試用例,它們正常工作。不知道爲什麼會出現這種行爲,我肯定在這裏丟失了一些東西。請指教。

+0

您是否想用'@ Test'註解(這是如何通過Junit 4測試方法的限定)而不是擴展'TestCase'(它早於Junit 4)? – Vikdor

+0

Vikdor,我註釋了@Test在這些類中的所有測試方法。這個TestCase類我擴展了套件。 – San

+0

對不起,我沒有意識到你想讓MyTestSuite成爲一個套件。使用'@RunWith(Suite.class)'運行測試套件。在你需要注入bean的測試用例中需要'@RunWith(SpringJunit4ClassRunner.class)'。 – Vikdor

回答

7

正如評論中所述,我們使用@RunWith(Suite.class)運行TestSuite,並使用@SuiteClasses({})列出所有測試用例。爲了在每個測試用例中不重複@RunWith(SpringJunit4ClassRunner.class)@ContextConfiguration(locations = {classpath:META-INF/spring.xml}),我們創建了一個AbstractTestCase,並在其上定義了這些註釋,併爲所有測試用例擴展了這個抽象類。樣本可以發現如下:

/** 
* An abstract test case with spring runner configuration, used by all test cases. 
*/ 
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = 
{ "classpath:META-INF/spring.xml" }) 
public abstract class AbstractSampleTestCase 
{ 
} 


public class SampleTestOne extends AbstractSampleTestCase 
{ 
    @Resource 
    private SampleInterface sampleInterface; 

    @Test 
    public void test() 
    { 
     assertNotNull(sampleInterface); 
    } 

} 


public class SampleTestTwo extends AbstractSampleTestCase 
{ 
    @Resource 
    private SampleInterface sampleInterface; 

    @Test 
    public void test() 
    { 
     assertNotNull(sampleInterface); 
    } 

} 


@RunWith(Suite.class) 
@SuiteClasses(
{ SampleTestOne.class, SampleTestTwo.class }) 
public class SampleTestSuite 
{ 
} 

如果你不希望有一個AbstractSampleTest,那麼你需要重複對每個測試用例春季亞軍註釋,直到春天類似於他們如何一SpringJunitSuiteRunner出現需要添加一個SpringJunitParameterizedRunner

+0

這與我最初做過的事情是一樣的,我在第一個代碼塊爲基類。我唯一缺少的是基礎類的抽象,現在我添加了它。但是,仍然看到下面的錯誤。 「java.lang.NoClassDefFoundError:junit/framework/Test」這是與classpath相關的東西。但是我的junit任務classpath顯示的是jar junit 4.8。我錯過了什麼或者我的類路徑錯了嗎? – San

+0

註解'Test'應該解析爲'org.junit.Test'。不知道爲什麼它是你的情況下的'junit.framework.Test'。你能相應地改變進口嗎? – Vikdor