1

I have a simple enough problem. In my unit test I compare expected vs actual output as a String value. Now part of the string is a randomly generated unique ID which causes the test to fail every time. Is there a way I can specify my test to only match part of the actual and ignore text between two points in the string. A function like -

def isMatch(expected : String, actual : String , ignoreFrom : String , ignoreTo : String)

Also, since this is a candidate for pattern matching, could some one point me to a pattern match/regex for Dummies kind of a tutorial?

2
  • Visit this links it will be helpfull for you link1 link2 Commented Oct 11, 2013 at 7:57
  • ignoreFrom is String or Int? Commented Oct 11, 2013 at 8:41

2 Answers 2

2

I think Scala extractors is what you want. You can specify extractor to match only specific part of the string.

Here is some example:

object IgnoreBetween {
    def unapply(str: String): Option[(String, String)] = {
        val parts = str split "\\."
        if (parts.length == 3){
            Some(parts(0), parts(2))
        }else{
            None
        }
    }
}

object Main extends App {
    "part1.somerandom.part2" match {
        case IgnoreBetween("part1", "part2") => println("matches")
        case _ => println("doesn't match")
    }
}

"Programming in Scala" and "Scala in depth" have amazing examples on pattern matching.

Sign up to request clarification or add additional context in comments.

Comments

0

We have created our custom matchers to deal with variable strings, basically using regex to express the expected outcome for a test. The cases where this is useful are plenty: A variable ID like in your case, different server URL's like when we run tests in QA lines, dates,...

What you want is some generic pattern matcher, something like:

def matches(expected : String, actual : String) = {
    val pattern = expected.r.pattern
    pattern.matcher(actual).matches
}

Example usage (on the REPL):

scala> matches("user id='(.+)' retrieved", "user id='12345' retrieved")
res1: Boolean = true

scala> matches("user id='(.+)' retrieved", "user id='12345' not found")
res2: Boolean = false

1 Comment

We use cucumber for testing, and this resource is quite OK on simple regex usage for test purposes. It's cucumber related, but gives you a good idea on how to match expected inputs: richardlawrence.info/2010/07/20/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.