I want to compare a string content with string interpolation. The string interpolation is for example
s"Hello ${name} ,
Your order ${UUID} will be shipped on ${date}."
There are some constraints that can be expressed in regular expressions.
The date
is in this format 2018-03-19T16:14:46.191+01:00 ( +%Y-%m-%dT%H:%M:%S ).
The UUID
is randomized and follows this format 834aa5fd-af26-416d-b715-adca01a866c4 .
One possible solution is to check if the string result contains some fixed part of the String interpolation.
Question
Constraint : you don't know in advance the parameters values in the String interpolation.
How would you check the value of a String interpolation ?
In general, how to test a String comparison with String interpolation if you don't know in advance the parameters values?
The solution can be given in Java. Scala is preferred.
You could define the variables in your test. For example, with the following function:
def stringToTest(name: String, UUID: String, date: String): String = {
s"Hello ${name}, Your order ${UUID} will be shipped on ${date}."
}
You could write a test like this (assuming you're using something like FlatSpec with Matchers
in your tests):
"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."
}
}
You should be able to test each function independently, and able to use dummy values passed into the function without a problem. If you are using truly random values though (or want to over-complicate your tests), I guess you could use a regex check. Easiest way I've found is something like this:
"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
}
}