Search code examples
javajunit

How to assert that an expression does not compile


I have written a piece of framework that adds the possibility for type-safe invocations of its interface. Now, when writing the JUnit tests, I want to show that specific expressions that earlier led to runtime errors are checked by the compiler now.

// this does not compile, because nameProp is of type Property<String>
Integer name = interface.getProperty(nameProp);

Probably it'd be best to simply comment that code out and leave it like that. I was just wondering whether it'd be possible with some testing framework to write something like

assertCompilationError() {
     Integer name = interface.getProperty(nameProp);
}

I explicitly do not want to fiddle around with invocations of javac with a custom classpath myself. If there is the possibility for a general solution that could be extracted to framework code (and donated to JUnit or TestNG) such a solution would be welcome as well.


Solution

  • After some time, I found following piece of software:

    https://janino-compiler.github.io/janino/

    It looks like it should be possible to do some sort of hack in order compile only the block in question. Right now, my example would not work, anyway, because it yet does not support generics.