2012-09-14 138 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