11

What is the proposed way of performing tests on scala macros?

I realize that one needs two projects due to the necessity of separate compilation. This step, if necessary, is acceptable and mostly clear.

But how do you assert a macro expansion fails when it should? Without some special facility, the test case won't compile and therefore the whole test project won't compile.

I think this assert would require another macro of the form

errors(code: => _): List[CompileError]

which returns the compile errors of the inner macro. The same would be required for testing that warnings occur if they should and so on...

Are there some existing testing facilities for Scala macros?

Martin Ring
  • 5,404
  • 24
  • 47
  • 4
    +1. See also [this question about testing for non-compilation in Scala](http://stackoverflow.com/q/15125457/334519) and [this one about documenting Scala macros](http://stackoverflow.com/q/13840784/334519). – Travis Brown Apr 02 '14 at 12:42
  • The former question does have promising answers. Thanks for the pointer! – Martin Ring Apr 02 '14 at 14:36

2 Answers2

3

You can use assertDoesNotCompile from ScalaTest. Here is an example of using this to test the Scala typechecker:

import org.scalatest.FunSuite

class TypeTest extends FunSuite {
  test("String vals can't hold ints") {
    assertDoesNotCompile("val x: String = 1")
  }
}

You can pass a string containing an example of when your macro expansion should fail to assertDoesNotCompile. Note that that there is also assertCompiles, if you feel the need for that.

Brian McCutchon
  • 8,354
  • 3
  • 33
  • 45
1

you could use twitter eval to check if the code copiles

https://github.com/twitter/util/blob/master/util-eval/src/main/scala/com/twitter/util/Eval.scala#L247

Guillaume Massé
  • 8,004
  • 8
  • 44
  • 57