Static Testing for Scala

There are some good libraries for testing in Scala ( Specs , ScalaTest , ScalaCheck ). However, with Scala's powerful type system, important parts of the API developed by Scala are expressed statically, usually in the form of some unwanted or forbidden behavior prevented by the compiler.

So what is the best way to check if the compiler prevents the compiler from developing a library or other API? It is not enough to comment on the code, which must be incompatible, and then uncomment it for verification.

Customized Listing Test Example:

val list: List[Int] = List(1, 2, 3)
// should not compile
// list.add("Chicka-Chicka-Boom-Boom")

Does one of the existing test libraries support such cases? Is there an approach that people use that works?

The approach that I was considering was to embed the code in a string with a triple quote or xml element and call the compiler in my test. The call code looks something like this:

should {
  notCompile(<code>
    val list: List[Int] = List(1, 2, 3)
    list.add("Chicka-Chicka-Boom-Boom")
  </code>)
}

Or something on the expect -type script line is called in the interpreter.

+3
source share
1 answer

I created some specifications by executing some pieces of code and checking the results of the interpreter.

You can look at Snippets . The idea is to save in some org.specs.util.Property [Snippet] code for execution:

val it: Property[Snippet] = Property(Snippet(""))
"import scala.collection.List" prelude it // will be prepended to any code in the it snippet
"val list: List[Int] = List(1, 2, 3)" snip it // snip some code (keeping the prelude)
"list.add("Chicka-Chicka-Boom-Boom")" add it  // add some code to the previously snipped code. A new snip would remove the previous code (except the prelude)

 execute(it) must include("error: value add is not a member of List[Int]") // check the interpreter output

, , . , .

.

+7

Source: https://habr.com/ru/post/1724903/


All Articles