user9683185
user9683185

Reputation:

write a test for scala code

I am learning how to do unit tests with scalatest , but I have some basic questions as I am learning Scala/Scalatest I wrote one scala script which has one scala object with several methods. My question is as follows: Should I write one unit test for the whole Scala object or should I write a test per function. For example I wrote the following function : Do you know how to write a test with scala test for this specific function:

def dataProcessing (input: List[String]) = {



val Data = input.map(_.trim).filter(x => !(x contains "$")).filter(line => Seq("11", "18").exists(s => line.contains(s))).map(elt => elt.replaceAll("""[\t\p{Zs}\.\$]+""", " ")).map(_.split("\\s+")).map(x => (x(1),x(1),x(3),dataLength(x(3)),dataType(x(3))))

 return Data
}

Finally I am trying to use the test driven design best practices but still don't know how to proceed to write tests before writing code , Any tips how to proceed to be compliant with these practices.

Many thanks

Upvotes: 0

Views: 1285

Answers (1)

tilde
tilde

Reputation: 913

In general, when you define a class or object, you should write tests for the methods someone using that class should call, and the other methods should be private. If you find yourself wanting to make methods public, just so they can be tested, consider moving them to a separate class or object.

There are a lot of testing styles supported by scala test. Personally, I like WordSpec. A basic test in progress would look like this:

class MyTest extends WordSpec with Matchers {
  "My Object" should {
    "process descriptors" when {
      "there is one input" in {
        val input = List("2010 Ford Mustang")

        val output = MyObject.descriptorProcessing(input)

        output should have length 1
        output.head shouldBe()
      }

      "there are two inputs" in pendingUntilFixed {
        val input = List("Abraham Joe Lincoln, 34, President",
                         "George Ronald Washington, 29, President")

        val output = MyObject.descriptorProcessing(input)

        output should have length 2
        output.head shouldBe()
      }
    }

    "format descriptors" when {
      "there is one input" in pending
    }
  }
}

I've used two features of scalatest that enable TDD, pendingUntilFixed and pending.

pendingUntilFixed lets you write a test for code that hasn't been implemented yet, or isn't working correctly yet. As long an assertion in the test fails, the test is ignored and displayed in yellow output. Once all the assertions pass, the test fails, letting you know that you can turn it on. This enables TDD, while allowing your build to pass before work is completed.

pending is a marker saying "I'm going to write a test for this, but I haven't gotten to it yet". I use this a lot, as it allows me to write an outline for my tests, then go back and fill them in.

Upvotes: 2

Related Questions