【问题标题】:Mock function's behvaiour in Mocktio ScalaMockito Scala 中的模拟函数行为
【发布时间】:2018-09-28 03:21:07
【问题描述】:

我正在开发一个 Scala 和 Play 应用程序,并尝试为我的一个单元测试编写一个模拟。

def getActionAsBase64(
    appName: String = null,
    taskType: String = null,
    taskName: String = null
  ): String = {
    val pwd = System.getProperty("user.dir")
    val filePath = Paths.get(pwd, "..", "tasks", appName, taskType, taskName, taskName + ".zip").toString
    val simplified = Files.simplifyPath(filePath)

    // Reading the file as a FileInputStream
    val file = new File(simplified)
    val in = new FileInputStream(file)
    val bytes = new Array[Byte](file.length.toInt)
    in.read(bytes) // stream inserts bytes into the array
    in.close()

    // Encoding the file using Base64encoder
    val encoded =
      new BASE64Encoder()
        .encode(bytes)
        .replace("\n", "")
        .replace("\r", "")
    return encoded.toString
  }

以上是我的原始代码,我试图模拟in.read 的行为,并使其向bytes 数组注入任意数据。

到目前为止,我只能找到如何使用 thenReturn 方法进行简单模拟,该方法模拟返回值。

在我的情况下,我想再次模拟函数的行为,理想情况下,它应该执行类似的操作

def mockRead(bytes) {
   // mutate the bytes parameter
}

【问题讨论】:

  • 您可能会发现函数getActionAsBase64本身可以改进,但我只是想学习如何模拟函数行为以供将来参考。提前致谢。

标签: scala playframework mockito


【解决方案1】:

您需要一种方法来注入模拟文件或读取文件的函数,

接受函数的 API 示例,

  import java.util.Base64

  object Api {

    def getActionAsBase64(fileBytesFn: (String, String, String) => Array[Byte],
                          appName: String,
                          taskType: String,
                          taskName: String): String = {

      val encoded = new String(Base64.getEncoder
        .encode(fileBytesFn(appName, taskName, taskName)))
        .replace("\n", "")
        .replace("\r", "")

      encoded
    }
  }

这样你就可以通过一个读取文件的测试函数,

  test("test a function") {

    val mock = (_: String, _: String, _: String) => "prayagupd".getBytes()

    val d = Api.getActionAsBase64(mock, "any app name", "taskName", "taskName")

    assert(d == "cHJheWFndXBk")
  }

另一种方法是传入stubbed func

  test("test a function II") {

    val stbbedFn = stubFunction[String, String, String, Array[Byte]]
    stbbedFn.when("any appName", "any taskType", "any taskName").returns("prayagupd".getBytes())

    val d = Api.getActionAsBase64(stbbedFn, "any appName", "any taskType", "any taskName")

    assert(d == "cHJheWFndXBk")
  }

【讨论】:

  • 我喜欢这个想法,它更实用,谢谢 =) 但是,我仍然很好奇如何模拟函数的行为......如果你知道如何实现它,请告诉我,谢谢。
  • 您可以使用stubFunction[Input, Output] 来模拟函数的行为。查看更新的示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多