简体   繁体   English

在 Junit 中测试不同的 Java 版本

[英]Testing different Java Versions in Junit

is there a way to specify the JVM version in a junit test, when multiple java types are available on an OS?当操作系统上有多个 java 类型时,有没有办法在 junit 测试中指定 JVM 版本?

I'd like to do something like this:我想做这样的事情:

@JVM=1.5
public void test1(){
   run();
}

@JVM=1.7
public void test2(){
   run();
}

etc.. ETC..

No, you'll have to run the JUnit tests multiple times with multiple VMs. 不,您必须使用多个VM多次运行JUnit测试。 You can then use Assume to only run the tests for the correct VM: 然后,您可以使用“ 假定”仅针对正确的VM运行测试:

public void test1(){
   // not compiled or tested
   Assume.assumeThat(System.getProperty("java.version"), CoreMatchers.startsWith("1.5"));
   run();
}

public void test2(){
   Assume.assumeThat(System.getProperty("java.version"), CoreMatchers.startsWith("1.7"));
   run();
}

Please note that I haven't compiled this, so there may be errors. 请注意,我尚未编译此文件,因此可能会出现错误。 Then, in your build tool, run these tests twice in two different VMs. 然后,在构建工具中,在两个不同的VM中运行这些测试两次。

On JUnit 5, you can use EnabledOnJre and DisabledOnJre annotations. JUnit 5、可以使用EnabledOnJreDisabledOnJre注解。

  @EnabledOnJre(JRE.JAVA_8)
  void testMyMethodInJava8() {
     ...
  }

  @DisabledOnJre(JRE.JAVA_8)
  void testMyMethodInOtherVersions() {
     ...
  }

You can also apply these to a whole test class:您还可以将这些应用于整个测试 class:

@EnabledOnJre(JRE.JAVA_11)
public class MyClassTest {
   ...
}

You still need to run the test suite separately for each JVM, but this allows you to skip the tests that will not work in one or the other.您仍然需要为每个 JVM 单独运行测试套件,但这允许您跳过在其中一个或另一个中不起作用的测试。

JUnit test cases are just a bunch of Java classes, not a standalone program. JUnit测试用例只是一堆Java类,而不是独立的程序。 So they would still be confined within the same JVM. 因此它们仍将被限制在同一JVM中。 AFAIK there is no simple way to do what you intend to do. AFAIK没有简单的方法可以完成您打算做的事情。 What you can do is separate the test cases into test suites for each java version you want to test for. 您可以针对要测试的每个Java版本,将测试用例分为多个测试套件。 Then change the java version in the project settings and run the appropriate test suites. 然后在项目设置中更改Java版本并运行适当的测试套件。

Also there is a junit.jvm property, but I am not sure if you can change it mid-execution. 也有一个junit.jvm属性,但是我不确定是否可以在执行期间更改它。 Have you taken a look at it? 你看过了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM