检查一个字符串是否匹配这个字符串插值

Check if a String matches this String interpolation

我想用字符串插值来比较字符串内容。 string interpolation 例如

s"Hello ${name} ,
Your order ${UUID} will be shipped on ${date}."

有些约束可以用正则表达式表达。

date 的格式为 2018-03-19T16:14:46.191+01:00 ( +%Y-%m-%dT%H:%M:%S )。

UUID 是随机的并遵循此格式 834aa5fd-af26-416d-b715-adca01a866c4 .

一种可能的解决方案是检查字符串结果是否包含字符串插值的某些固定部分。

问题

Constraint : 你事先不知道String插值中的参数值。

您将如何检查字符串插值的值?

一般来说,如果事先不知道参数值,如何测试字符串与字符串插值的比较​​?

解决方案可以在Java中给出。首选 Scala。

您可以在测试中定义变量。例如,使用以下函数:

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."
  }
}

您应该能够独立测试每个函数,并且能够毫无问题地使用传递给函数的虚拟值。如果您使用的是真正的随机值(或者想要 over-complicate 您的测试),我想您可以使用正则表达式检查。我发现的最简单的方法是这样的:

"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
  }
}