Testing an assertion that something must not compile

前端 未结 5 958
有刺的猬
有刺的猬 2020-12-04 09:52

The problem

When I\'m working with libraries that support type-level programming, I often find myself writing comments like the following (from an example presente

5条回答
  •  心在旅途
    2020-12-04 10:38

    Based on the links provided by Miles Sabin I was able to use the akka version

    import scala.tools.reflect.ToolBox
    
    object TestUtils {
    
      def eval(code: String, compileOptions: String = "-cp target/classes"): Any = {
        val tb = mkToolbox(compileOptions)
        tb.eval(tb.parse(code))
      }
    
      def mkToolbox(compileOptions: String = ""): ToolBox[_ <: scala.reflect.api.Universe] = {
        val m = scala.reflect.runtime.currentMirror
        m.mkToolBox(options = compileOptions)
      }
    }
    

    Then in my tests I used it like this

    def result = TestUtils.eval(
      """|import ee.ui.events.Event
         |import ee.ui.events.ReadOnlyEvent
         |     
         |val myObj = new {
         |  private val writableEvent = Event[Int]
         |  val event:ReadOnlyEvent[Int] = writableEvent
         |}
         |
         |// will not compile:
         |myObj.event.fire
         |""".stripMargin)
    
    result must throwA[ToolBoxError].like {
      case e => 
        e.getMessage must contain("value fire is not a member of ee.ui.events.ReadOnlyEvent[Int]") 
    }
    

提交回复
热议问题