【问题标题】:write a test for scala code为 scala 代码写一个测试
【发布时间】:2018-10-06 00:28:52
【问题描述】:

我正在学习如何使用 scalatest 进行单元测试,但是我在学习 Scala/Scalatest 时遇到了一些基本问题 我写了一个 scala 脚本,它有一个带有多种方法的 scala 对象。我的问题如下:我应该为整个 Scala 对象编写一个单元测试,还是应该为每个函数编写一个测试。 例如我写了以下函数: 你知道如何用 scala test 为这个特定的功能写一个测试吗:

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
}

最后我尝试使用测试驱动设计最佳实践,但在编写代码之前仍然不知道如何继续编写测试,任何提示如何继续符合这些实践。

非常感谢

【问题讨论】:

  • 与您的问题没有直接关系,但我会避免写这么长的行。要么定义一些中间的vals,要么至少将每个方法拆分到一个新行。
  • 另一种可能性是定义私有辅助方法来执行一些单独的步骤。这些应该被命名以清楚地描述它们的作用。
  • 另外,考虑定义一个案例类来保存你的输出,而不是返回一个 5 元组。像这样的东西:case class Descriptor(firstName: String, middleName: String, lastName: String, age: Int, jobTitle: String)
  • 至于问题的 TDD 部分 - TDD 背后的整个理念是,您在开始编写代码之前就知道成功是什么样的。因此,当您认为要定义 dataProcessing 时,您可能知道您对它的输入和输出应该是什么样子。有了这些知识,您应该能够编写一个测试来说明当我喂它 X 时,我得到 Y 作为结果。因此,您按照@tilde 在他的回答中概述的方式设置您的测试,然后您看到它失败 - 然后编写足够的代码使其通过。

标签: scala unit-testing tdd scalatest


【解决方案1】:

一般来说,当你定义一个类或对象时,你应该为使用该类的人应该调用的方法编写测试,而其他方法应该是私有的。如果您发现自己想要公开方法,以便对其进行测试,请考虑将它们移动到单独的类或对象中。

scala test 支持很多测试风格。就个人而言,我喜欢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
    }
  }
}

我使用了两个启用 TDD 的 scalatest 功能,pendingUntilFixedpending

pendingUntilFixed 允许您为尚未实现或尚未正常工作的代码编写测试。只要测试中的断言失败,测试就会被忽略并以黄色输出显示。一旦所有的断言都通过了,测试就会失败,让你知道你可以打开它。这将启用 TDD,同时允许您的构建在工作完成之前通过。

pending 是一个标记,表示“我要为此编写一个测试,但我还没有完成”。我经常使用它,因为它可以让我为我的测试写一个大纲,然后回去填写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-02
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    相关资源
    最近更新 更多