How to unit test the code that should cause a compilation error

I have a class that takes an ArrayList parameter as a parameter:

public class Foo {
    private ArrayList<Bar> bars;

    public Foo(ArrayList barList) {
        bars = barList;
    }
}

      

there is an error that I can pass any ArrayList to the constructor:

// should compile error with this line
Foo foo = new Foo(new ArrayList<String>());

      

the problem is that if I add this case to the test suite when the bug is fixed, I cannot compile it. is there anyway to check this case?

+3


source to share


3 answers


I don’t know of any language / unit test framework that will allow you to "test" code that should not compile. If you can't compile it, there is nothing to test. However, you can include all compiler warnings on creation. I'm pretty sure passing a non-parameterized collection is a big warning in any JVM after JDK5.



+3


source


I think this is bad practice and I don't see anything in common, but see this example for how to check for compilation errors:

import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class CompileTest {

    //A very naive way checking for any error
    @Test(expected=java.lang.Error.class)
    public void testForError() throws Exception {
        this.is.not.a.statement;
    }

    //An example which check that we only find errors for regarding compilation errors.
    @Test
    public void expectNotCompilableMethod() {
        try {
            uncompilableMethod();
            fail("No compile error detected");
        } catch (Error e) {
            assertTrue("Check for compile error message", e.getMessage().startsWith("Unresolved compilation problems"));
        }
    }

    private void uncompilableMethod() {
        do.bad.things;
    }
}

      



Edit: 1) I'm not sure how this might behave along with building tools like maven. As far as I know, maven breaks build on compilation errors, so it probably won't even run tests.

+1


source


Correct your method signature:

public Foo(ArrayList<Bar> barList) {
    bars = barList;
}

      

The problem has been resolved. (You probably want to check for null as well.)

0


source







All Articles