【问题标题】:Adding a @Test method dynamically to junit test class将@Test 方法动态添加到junit 测试类
【发布时间】:2013-01-30 14:41:26
【问题描述】:

我们有一个文本文件,其中给出了搜索查询列表和预期结果。比如,

搜索结果

a:120         result1
b:220         result2
.....
.....

现在,我们需要编写一个 JUnit(在我们的日常构建中大量使用)测试类,其中每一行将代表一个 @Test method。因此,我们知道哪个搜索案例失败(UI)。

我们已经有了一个解决方案,我们只有一个 @Test 方法,并且我们有日志来检查哪个案例通过或失败。

但是,我们正在尝试实现每个案例都表示为一个 junit 方法。是否真的可以为 JUnit 架构动态创建 @Test 方法。

我们的@Test 方法对于每个搜索案例都是相同的。这意味着,我们只想每次都传递一个不同的参数。

我想出了一个 JUnit3 解决方案来解决我的问题。需要帮助将其翻译成 Junit4。

public static Test suite()
   {
      TestSuite suite = new TestSuite();
      for ( int i = 1; i <= 5; i++ ) {

         final int j = i;
         suite.addTest(
            new Test1( "testQuery" + i ) {
               protected void runTest()
               {
                  try {
                     testQuery( j );
                  } catch ( MalformedURLException e ) {

                     // TODO Auto-generated catch block
                     e.printStackTrace();
                  } catch ( SolrServerException e ) {

                     // TODO Auto-generated catch block
                     e.printStackTrace();
                  }
               }
            }
            );
      }

      return suite;
   }

【问题讨论】:

    标签: junit junit4 junit3


    【解决方案1】:

    在 JUnit 4 中有一个名为“参数化测试”的概念正是用于此目的。

    我不完全理解你上面的测试,但这应该给你一个提示:

    @RunWith(Parameterized.class)
    public class ParameterizedTest {
    
        private String query;
        private String expectedResult;
    
        public ParameterizedTest(String query, String expectedResult) {
            this.query = datum;
            this.expectedResult = expectedResult;
        }
    
        @Parameters
        public static Collection<Object[]> generateData() {
            Object[][] data = {
                    { "a:120", "result1" },
                    { "b:220", "result2" },
            };
            return Arrays.asList(data);
        }
    
        @Test
        public void checkQueryResult() {
            System.out.println("Checking that the resutl for query " + query + " is " + expectedResult);
            // ...
        }
    
    }
    

    【讨论】:

    • 谢谢,这正是我所需要的。我的工作完成了。无论如何我们可以命名测试,类似于我的 Junit3 示例?即 testQuery1、testQuery2 等。
    • @kma,是的,看看 4.11 版本,您可以在参数注释中指定名称作为数据的函数,使用“{0}”作为数组中的第一个对象等.
    猜你喜欢
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 2023-03-20
    相关资源
    最近更新 更多