关于junit:如何编写包含多个测试的Spring测试套件并运行选择性测试?

How to write spring test suite of multiple tests and run selective tests?

我在一个测试班上有很多弹簧测试方法。我只想运行选择性测试。所以我想在同一个类中创建一个测试套件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/testApplicationContext.xml"})
@TransactionConfiguration(defaultRollback=true)
public class TestersChoice  {


@Test
@Transactional
public void testAddAccount(){        
  ///do something ....
}  


@Test
@Transactional
public void testDeleteAccount(){        
  ///do something ....
}  

@Test
@Transactional
public void testReadAccount(){        
  ///do something ....
}

} ??

如果我运行此Class TestersChoice,则所有测试都将运行!我只想运行testReadAccount而不是其余的。我想创建套件以运行选择性测试。 (我想避免删除上述测试方法中的@Test来实现此目的)
jUnit测试用例中的内容。通过将TestersChoice类扩展到TestCase并插入此方法,我能够做到这一点:

1
2
3
4
5
public static TestSuite suite(){
      TestSuite suite = new TestSuite();
       suite.addTest(new TestersChoice("testDeleteAccount"));
      return suite;
}

但是由于我现在没有扩展TestCase,所以无法将TestersChoice实例添加到套件中!

如何运行选择性测试?


您可以使用Spring的IfProfileValue(如果您始终使用@RunWith(SpringJUnit4ClassRunner.class)),然后仅在使用-D<propertyname>指定特定的系统属性时才能运行测试。


如果您想要对测试进行分组,那么问题不在于spring-test,而在于无法对测试进行分组的JUnit。考虑切换到TestNG(也由Spring OOTB支持)。

TestNG基于JUnit构建,但功能强大得多:请参见比较。

分组很容易。

致谢,
Stijn


在每个不想执行的方法上使用@Ignore。以您的示例为例:

1
2
3
4
5
6
7
8
9
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"/testApplicationContext.xml"}) @TransactionConfiguration(defaultRollback=true) public class TestersChoice  {


@Test  @Transactional @Ignore public void testAddAccount(){           ///do something .... }  


@Test @Transactional @Ignore public void testDeleteAccount(){          ///do something .... }  

@Test @Transactional public void testReadAccount(){           ///do something .... }

所有标记为@Ignore的方法将不执行