动态测试Java或Scala中的生成

时间:2016-03-08 08:51:29

标签: json scala junit scalatest specs2

我有一个包含测试列表的大型json文件。 Json文件包含多个文件名,其中包含测试类的名称,其中包含一些设置内容和一组测试。以下是此类json文件的示例:

{
   "filename1.py": {
     "ClassName": [
       "setupSection": [
         here will be list of sqls which should be performed before tests
        ],
   "listOfTests": {
     "test1Name": [
        { here will be query }, {here will be expected result}
     ],
     "test1Name": [
        { here will be query }, {here will be expected result}
     ]
    }
   },
  "filename2.py": {
     "ClassName": [
       "setupSection": [
         here will be list of sqls which should be performed before tests
        ],
   "listOfTests": {
     "test1Name": [
        { here will be query }, {here will be expected result}
     ],
     "test1Name": [
        { here will be query }, {here will be expected result}
     ]
    }
   }
}

我需要以某种方式使用Java或Scala编写的几个类来执行此测试。所以应该有1-3个用Java或/和Scala编写的类,它们将从json文件执行所有测试。有可能吗?

1 个答案:

答案 0 :(得分:3)

可以使用specs2。我们假设你可以将你的Json文件反序列化为

case class Query(query: Query)
case class Test(name: String, query: Query, result: String)
case class TestFile(setup: Query, tests: List[Test])

然后您可以创建以下规范

import org.specs2._

class JsonSpec(path: String) extends Specification {
   lazy val files: List[TestFile] = readFilesFromJson(path)

   def createTests(tests: List[Test]): Fragments = 
     Fragments.foreach(tests) { test =>
       s2"""|
            |${test.name ! executeQuery(test.query) must_== test.result}""".stripMargin
     }

   def is = 
     Fragments.foreach(files) { file =>
     s2"""|
          |${step(executeQuery(file.setup))}
          |${createTests(file.tests) 
     """.stripMargin
   }

   // load the Json file
   def readFilesFromJson(path: String): List[TestFile] =
     ???

   // execute the query and return the result
   // as a String
   def executeQuery(query: Query): String = 
     ???
}

如果您有任何问题,请创建一个小型Github项目,我可以从那里帮助您。