您可以在测试中定义变量。例如,使用以下功能:
def stringToTest(name: String, UUID: String, date: String): String = {
s"Hello ${name}, Your order ${UUID} will be shipped on ${date}."
}
您可以编写这样的测试(假设您使用的是
FlatSpec with Matchers
在您的测试中):
"my function" should {
"return the correct string" in {
val name = "Name"
val UUID = "834aa5fd-af26-416d-b715-adca01a866c4"
val date = "2018-03-19T16:14:46.191+01:00"
stringToTest(name, UUID, date) shouldBe "Hello Name, Your order 834aa5fd-af26-416d-b715-adca01a866c4 will be shipped on 2018-03-19T16:14:46.191+01:00."
}
}
您应该能够独立地测试每个函数,并且能够使用传递到函数中的伪值而不会出现问题。如果您使用的是真正的随机值(或者想要使测试过于复杂),我想您可以使用regex检查。我找到的最简单的方法是:
"this string" should {
"match the correct regex" in {
val regex = "^Hello .*, " +
"Your order .{8}-.{4}-.{4}-.{4}-.{12} will be shipped on " +
"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}\+\d{2}:\d{2}\.$" // whatever
val thingToCheck = "Hello Name, " +
"Your order 834aa5fd-af26-416d-b715-adca01a866c4 will be shipped on " +
"2018-03-19T16:14:46.191+01:00."
thingToCheck.matches(regex) shouldBe true
}
}