【问题标题】:How to write scalatest unit test for scala object? [closed]如何为 scala 对象编写 scalatest 单元测试? [关闭]
【发布时间】:2018-12-15 22:42:24
【问题描述】:

我正在尝试使用 scalatestscala 对象 编写单元测试,但是。 我为我的sbt 导入了以下依赖项;

libraryDependencies += "org.scalactic" %% "scalactic" % "3.0.5" libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % "test"

如何为这段代码编写测试用例?

object Word {

  def readFile(): Map[String, Int] = {
    val counter = scala.io.Source.fromFile("filepath")
      .getLines.flatMap(_.split("\\W+"))
      .foldLeft(Map.empty[String, Int]) {
        (count, word) =>
          count + (word ->
            (count.getOrElse(word, 0) + 1))
      }
    counter
  }
}

【问题讨论】:

  • 你想问什么?请在您的问题中添加详细信息您面临什么问题?
  • 感谢您的回复。在这里我想问一下,使用上述依赖项我需要为 scala 对象实现一个测试用例,如下所示:
  • 没关系,但您遇到了什么问题?实际上,只有在任何人都可以帮助您的情况下,才能为您的问题提供更多信息。
  • def readFile(): Map[String, Int] ={ val counter = scala.io.Source.fromFile("Data\\Reading.txt") .getLines .flatMap(_.split("\\W+")) .foldLeft(Map.empty[String, Int]){ (count, word) => count + (word -> (count.getOrElse(word, 0) + 1)) } return counter }
  • 所以我需要在object Word中为上述方法实现sacalatest

标签: scala unit-testing scalatest


【解决方案1】:

有很多方法可以为它编写测试。有 FlatSpec、FunSuit 等库。 所以在这里,我将使用 FunSuit 为它编写测试用例

import org.scalatest.FunSuite

class WordTest extends FunSuite {

  test("should return word count ") {
    val wordCount = Word.readFile()

    assert(wordCount.nonEmpty)
  }
}

【讨论】:

    猜你喜欢
    • 2019-02-15
    • 2018-05-08
    • 1970-01-01
    • 2011-11-14
    • 1970-01-01
    • 2011-03-16
    • 2014-07-05
    • 2015-06-27
    相关资源
    最近更新 更多