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

后端 未结 3 1845
别那么骄傲
别那么骄傲 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 20:57

    Travis Brown's answer is absolutely correct. Just in the interest of completeness, I want to add that this also works for testing macros, as demonstrated here.

    One minor point: the illTyped check doesn't seem to work in the repl. It never throws an error, even if the given expression does type check. But don't let that fool you, it does work well.

    > test:console
    Welcome to Scala version 2.10.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_65).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> def foo(s: String) = s
    foo: (s: String)String
    
    scala> import shapeless.test.illTyped
    import shapeless.test.illTyped
    
    scala> foo(1)
    :10: error: type mismatch;
     found   : Int(1)
     required: String
                  foo(1)
                      ^
    
    scala> illTyped("""foo(1)""")
    
    scala> illTyped("""foo("hi there")""")  // <--- works, but shouldn't!
    

提交回复
热议问题