我创建了一个 Junit 测试,其中 Test 类具有一些变量,例如:
私有最终字符串版本=“0.25.1”
当我运行测试时,它会比较与此版本相关的文件。
还有一个 init() 方法。
目前我如何通过更改版本的值来测试另一个版本
手动设置为“0.24.1”和“0.24.0”,以便我可以检查所有这些版本的测试结果。
有没有办法指定版本列表,然后对每个版本运行测试并查看结果?
这是一个 Spring Boot 项目。
这是我编写的 Junit 测试的最小代码:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = Application.class)
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-local.yml")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MDServiceTest {
@Autowired
private MDService MDService;
private List<File> MDFiles;
private final String version = "0.24.1";
private final String MDType="WLCR";
@BeforeAll
public void init() throws IOException, InterruptedException {
MDFiles = MDService.generateMDFiles(version, MDType);
}
@Test
void testMetaAttributeFile() throws IOException {
File MDAttribFile = MDFiles.get(0);
String filePath = String.format("src/%s/%s_%s.csv", version, MDType,version);
File expectedMDAttribFile = new File(filePath);
Assert.assertTrue(Utility.compareCsvFiles(expectedMDAttribFile, MDAttribFile));
}
@Test
void testZip() throws IOException, InterruptedException {
List<File> MDFiles = MDService.generateMDFiles("0.24.1", "WLCR");
String zipFileName = "test.zip";
File file = Utility.zipIt(MDFiles, zipFileName);
Assert.assertEquals(zipFileName, file.getName());
}
}
我需要修改它,以便它针对所有版本号自动运行。可能要使用parameterizedTest,我必须修改此类,因为init方法也使用该版本,并且@ParameterziedTest可能无法应用于它。
您可以使用参数化测试。它对不同的参数运行相同的测试。
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
public class YourTestClass {
private YourClassToTest yourClassToTest;
@BeforeEach
public void init() {
yourClassToTest = new YourClassToTest();
}
@ParameterizedTest
@MethodSource("versions")
public void testWithDifferentVersions(String version) {
// Set the version in your test class based on the parameter
yourClassToTest.setVersion(version);
// Your test assertions
}
static Stream<String> versions() {
return Stream.of("0.25.1", "0.24.1", "0.24.0");
}
}