【发布时间】: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