我正在学习如何使用scalatest进行单元测试,但我有一些基本的问题,因为我正在学习Scala/Scalatest我编写了一个scala脚本,其中包含一个scala对象和几个方法。我的问题如下:我应该为整个Scala对象编写一个单元测试,还是应该为每个函数编写一个测试。例如,我编写了以下函数:您知道如何使用scala测试为此特定函数编写测试吗:
def dataProcessing (input: List[String]) = {
val Data = input.map(_.trim).filter(x => !(x contains "$")).filter(line => Seq("11", "18").exists(s => line.contains(s))).map(elt => elt.replaceAll("""[\t\p{Zs}\.\$]+""", " ")).map(_.split("\\s+")).map(x => (x(1),x(1),x(3),dataLength(x(3)),dataType(x(3))))
return Data
}最后,我尝试使用测试驱动的设计最佳实践,但仍然不知道如何在编写代码之前继续编写测试,以及如何继续遵循这些实践的任何提示。
非常感谢
发布于 2018-05-04 23:32:56
通常,在定义类或对象时,应该为使用该类的人应该调用的方法编写测试,而其他方法应该是私有的。如果您发现自己想要使方法成为公共的,只是为了测试它们,可以考虑将它们移到单独的类或对象中。
scala测试支持很多测试样式。就我个人而言,我喜欢WordSpec。正在进行的基本测试如下所示:
class MyTest extends WordSpec with Matchers {
"My Object" should {
"process descriptors" when {
"there is one input" in {
val input = List("2010 Ford Mustang")
val output = MyObject.descriptorProcessing(input)
output should have length 1
output.head shouldBe()
}
"there are two inputs" in pendingUntilFixed {
val input = List("Abraham Joe Lincoln, 34, President",
"George Ronald Washington, 29, President")
val output = MyObject.descriptorProcessing(input)
output should have length 2
output.head shouldBe()
}
}
"format descriptors" when {
"there is one input" in pending
}
}
}我使用了scalatest的两个支持测试驱动开发的特性:pendingUntilFixed和pending。
pendingUntilFixed允许您为尚未实现的代码或尚未正确工作的代码编写测试。只要测试中的断言失败,测试就会被忽略,并以黄色输出显示。一旦所有断言都通过,测试就会失败,让您知道可以打开它。这将启用TDD,同时允许您的构建在工作完成之前通过。
pending是一个标记器,表示“我将为此编写一个测试,但我还没有达到这个目的”。我经常使用它,因为它允许我为我的测试写一个大纲,然后回去填写它们。
https://stackoverflow.com/questions/50023789
复制相似问题