如何对应该导致编译错误的代码进行单元测试

how to unit test code that should cause compile error

我有一个 class 以 ArrayList 作为参数:

public class Foo {
    private ArrayList<Bar> bars;

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

有一个错误,我可以将任何 ArrayList 传递给构造函数:

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

问题是如果我将这个案例添加到测试套件中,当错误修复后,我无法编译它。 无论如何要测试这个案例?

修正你的方法签名:

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

问题已解决。 (您可能还想检查空值。)

我觉得这是一种不好的做法,我没有真正看到它的用处,但请参阅此示例以了解如何测试编译错误:

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;
    }
}

编辑: 1) 我不确定这与像 maven 这样的构建工具一起使用会如何表现。据我所知,maven 会在编译错误时中断构建,因此可能甚至不会执行测试。

我不知道有任何 language/unit 测试框架可以让您 "test" 获取不应编译的代码。如果你不能编译它,就没有什么可以测试的。但是,您可以在构建时打开所有编译器警告。我很确定在 JDK5 之后的任何 JVM 中传递未参数化的集合都是一个很大的警告。