当使用JUnit的@Parameterized时,我可以让一些测试仍然只运行一次

在许多情况下,我使用@Parameterized对许多排列运行测试。 这非常有效并且使测试代码本身变得简单和干净。

但是有时候我想让一些测试方法只运行一次,因为它们没有使用参数,JUnit是否有办法将测试方法标记为“singleton”或“run-once”?

注意:这不涉及在Eclipse中运行单个测试,我知道如何做到:)

您可以使用套件将任意数量的测试类关联起来。 这样,当您测试课程时,所有测试都会运行,您可以混合不同的测试跑步者。

  1. 创建与您正在测试的类关联的测试套件
  2. 添加对参数化测试类的引用
  3. 添加包含非参数化测试的其他类。

     import org.junit.runners.Suite; import org.junit.runner.RunWith; @RunWith(Suite.class) @Suite.SuiteClasses({ParameterizedTestClass.class, UnitTests.class, MoreUnitTests.class}) public class SutTestSuite{ //Empty... } 

您可以使用Enclosed runner来构建测试。

 @RunWith(Enclosed.class) public class TestClass { @RunWith(Parameterized.class) public static class TheParameterizedPart { @Parameters public static Object[][] data() { ... } @Test public void someTest() { ... } @Test public void anotherTest() { ... } } public static class NotParameterizedPart { @Test public void someTest() { ... } } } 

有一些junit插件可以为您提供有关参数化测试的更多function/function。 检查zohhak,junit-parames和junit-dataprovider。 它们允许您混合参数化和简单的junit测试

在我了解“@RunWith(Enclosed.class)”方法之前,我使用了以下(类似)解决方案,内部类扩展了外部类。 我一直在使用这种结构,因为我喜欢测试在同一个地方并分享一些属性和方法,事情对我来说似乎更清晰。 然后,使用Eclipse,在我的运行配置中,我选择“在所选项目,包或源文件夹中运行所有测试”选项,只需单击即可执行所有这些测试。

 public class TestBooksDAO { private static BooksDAO dao; @Parameter(0) public String title; @Parameter(1) public String author; @Before public void init() { dao = BooksDAO.getInstancia(); } /** Tests that run only once. */ public static class SingleTests extends TestBooksDAO { @Test(timeout=10000) public void testGetAll() { List books = dao.getBooks(); assertNotNull(books); assertTrue(books.size()>0); } @Test(timeout=10000) public void testGetNone() { List books = dao.getBooks(null); assertNull(books); } } /** Tests that run for each set of parameters. */ @RunWith(Parameterized.class) public static class ParameterizedTests1 extends TestBooksDAO { @Parameters(name = "{index}: author=\"{2}\"; title=\"{0}\";") public static Collection values() { return Arrays.asList(new Object[][] { {"title1", ""}, {"title2", ""}, {"title3", ""}, {"title4", "author1"}, {"title5", "author2"}, }); } @Test(timeout=10000) public void testGetOneBook() { Book book = dao.getBook(author, title); assertNotNull(book); } } /** Other parameters for different tests. */ @RunWith(Parameterized.class) public static class ParameterizedTests2 extends TestBooksDAO { @Parameters(name = "{index}: author=\"{2}\";") public static Collection values() { return Arrays.asList(new Object[][] { {"", "author1"}, {"", "author2"}, {"", "author3"}, }); } @Test(timeout=10000) public void testGetBookList() { List books = dao.getBookByAuthor(author); assertNotNull(books); assertTrue(books.size()>0); } } }