candied_orange
candied_orange

Reputation: 7334

Test for expected compile time errors in java

This question could be thought of as just the Java version of this c++ question: Unit test compile-time error

I'm writing some utility classes that mess with generics in java and things have gotten weird enough that I find myself wishing I knew how to write a unit test for code that is supposed to cause a compiler error. I know how to make a unit test pass only when the expected exception is thrown. No idea how to make it pass only when I get the expected error. Is this possible? If so, how? Is there a typical way of doing this? Is there a jUnit way?

An example would be using a method (lets say, one that performs a cast) in a way that should cause an error. I'd like a test that would only pass when the code calling that method produces an error. I'd run it along with other tests that should not cause an error.

As another example read Generic And Parameterized Types and note how the comments often say things like "fails with ClassClassException" "should fail, but succeeds". Those seem like tests that could be automated.

This is not to test the compiler. It's to test that the generic code I wrote does what it should do.

My gut tells me this goes beyond what the compiler or libraries could do and is into the realm of IDE magic, strange project configuration, or static code analysis. I really have no idea. I just want to be just as sure that the code causes the errors it should as I am that it's not causing the errors it shouldn't. I use eclipse, ant, and jUnit so an answer that details how this could be done with them would be perfect.

Upvotes: 2

Views: 1582

Answers (1)

j123b567
j123b567

Reputation: 3439

You can use another software to run some commands and check its results. It is then easy to check compile-time errors. It is possible to write it as a script in some language or as a separate project in java, but it must be distinct from your project.

Your commands to run should be javac, ant or any other depending on your IDE.

Upvotes: 3

Related Questions