升级到JUnit5时,我们面临一个限制:
@Test(expected = NullPointerException.class)
已经不可能了。这些天我们应该使用org.junit.jupiter.api.Assertions.assertThrows
。通常,它需要一个lambda,如果我们设置
android.compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
问题是,我们更愿意在发布版构建时停留在Java 7上(需要大量的测试才能证明我们仍然努力支持的所有古老设备在Java 8中正确工作)。
是否只有在Android中才有一种为单元测试设置sourceCompatibility
的干净方法?
发布于 2017-12-03 12:58:51
TL;NR:下面的代码适用于gradle任务,但是IDE不理解应用程序类不使用Java8。
在Android 3.0.1和gradle插件版本3.0.1中,以下工作如下:
tasks.all {
task ->
if (task.name.endsWith('UnitTestJavaWithJavac')) {
android.compileOptions.setSourceCompatibility(JavaVersion.VERSION_1_8)
android.compileOptions.setTargetCompatibility(JavaVersion.VERSION_1_8)
}
}
}
现在我可以写了
@Test
public void throwNPE() {
assertThrows(NullPointerException.class, () ->
{ int [] nullarr = null; nullarr.clone(); }
);
}
我的应用程序代码仍然保持在Java 7,甚至是Java 6。
对于check how Java compiler was actually configured,我可以在我的应用程序类和测试类上运行javap
:
javap -cp build/intermediates/classes/debug -verbose com.example.Main | grep major
javap -cp build/intermediates/classes/test/debug -verbose com.example.Tests | grep major
研究结果如下:
major version: 51
major version: 52
不幸的是,IDE不理解应用程序类不使用Java 8,并在以下情况下发出警告(请参阅Java8的undocumented example与Java 7不兼容):
interface I {}
public class Main implements I {
<T extends I> T getI() { return (T) this };
void foo(I value) {
System.out.println("foo(I)");
}
void foo(String value) {
System.out.println("foo(String)");
}
void warn() {
foo(getI());
}
}
尽管有此警告,“让Proect”和“Run Test”都通过了。
https://stackoverflow.com/questions/47535262
复制相似问题