How do I write a scala unit test that ensures compliation fails?

后端 未结 3 1826
别那么骄傲
别那么骄傲 2020-12-15 20:33

Is there any way to write something like a \"unit test\" which makes sure some code does not compile?

Why would I want such a thing? Two reasons.

1

3条回答
  •  时光取名叫无心
    2020-12-15 21:03

    Scalatest can also do this.

    Checking that a snippet of code does not compile

    Often when creating libraries you may wish to ensure that certain arrangements of code that represent potential “user errors” do not compile, so that your library is more error resistant. ScalaTest Matchers trait includes the following syntax for that purpose:

    "val a: String = 1" shouldNot compile
    

    If you want to ensure that a snippet of code does not compile because of a type error (as opposed to a syntax error), use:

    "val a: String = 1" shouldNot typeCheck
    

    Note that the shouldNot typeCheck syntax will only succeed if the given snippet of code does not compile because of a type error. A syntax error will still result on a thrown TestFailedException.

    If you want to state that a snippet of code does compile, you can make that more obvious with:

    "val a: Int = 1" should compile
    

    Although the previous three constructs are implemented with macros that determine at compile time whether the snippet of code represented by the string does or does not compile, errors are reported as test failures at runtime.

提交回复
热议问题