在 java junit 中创建 zip 文件的测试用例
Testcase for creating zip file in java junit
我编写了一个接受文件然后创建 zip 文件的方法。一旦 zip 文件创建完成,它就会尝试将其存储在 GCS 存储桶中并从临时目录中删除这些文件。
谁能帮我写一个测试用例。
private void createZip(File file) throws IOException {
File zipFile = new File(System.getProperty("java.io.tmpdir"), Constants.ZIP_FILE_NAME);
if (!file.exists()) {
logger.info("File Not Found For To Do Zip File! Please Provide A File..");
throw new FileNotFoundException("File Not Found For To Do Zip File! Please Provide A File..");
}
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
FileInputStream fis = new FileInputStream(file);) {
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
}
try {
// store to GCS bucket
GcpCloudStorageUtil.uploadFileToGcsBucket(zipFile, zipFile.getName());
file.delete();
zipFile.delete();
} catch (Exception e) {
logger.error("Exception" + e);
throw new FxRuntimeException("Exception " + e.getMessage());
}
}
作为设计测试用例时的一般经验法则,您既要考虑一切正常时的预期行为,又要考虑可能出错的每种方式的预期行为。
对于您的特定问题,当一切顺利时,您应该期望您的方法压缩作为参数给定的文件,上传它并从临时目录中删除该文件。
您可以通过监视静态 GcpCloudStorageUtil 方法来做到这一点。间谍是 class 的实例,除非指定,否则它们会保留其通常的行为,并且您可以监视哪些方法调用。您可以阅读更多关于 here and here(针对静态方法间谍)的主题。
如果不访问您的其余代码,很难给出一个完整的答案,但我建议:
- 正在创建一个非空文件
- 正在对此文件调用 createZip 方法
- 正在验证是否调用了 GcpCloudStorageUtil.uploadFileToGcsBucket 方法
- 正在验证上传的文件内容是否与您创建的文件匹配
- 正在验证临时目录现在是否为空
还有很多方法可能会出错。例如,作为参数给出的文件可能不存在。您想要编写一个测试用例,以确保在这种情况下抛出 FileNotFoundException。 article 涵盖了使用 JUnit4 或 JUnit5 执行此操作的不同方法。
同样,您可以设计一个测试用例,在其中模拟 GcpCloudStorageUtil.uploadFileToGcsBucket 并强制它抛出异常,然后验证是否抛出了预期的异常。模拟方法意味着强制它以某种方式运行(这里是抛出异常)。同样,您可以阅读有关 here.
主题的更多信息
编辑:这是一个可能的测试class。
@SpringBootTest
public class ZipperTest {
MockedStatic<GcpCloudStorageUtil> mockGcpCloudStorageUtil;
@Before
public void init(){
mockGcpCloudStorageUtil = Mockito.mockStatic(GcpCloudStorageUtil.class);
}
@After
public void clean(){
mockGcpCloudStorageUtil.close();
}
@Test
public void testFileIsUploadedAndDeleted() throws IOException, FxRuntimeException {
//mocks the GcpCloudStorageUtil class and ensures it behaves like it normally would
mockGcpCloudStorageUtil.when(() -> GcpCloudStorageUtil.uploadFileToGcsBucket(Mockito.any(File.class), Mockito.anyString())).thenCallRealMethod();
Zipper zipper = new Zipper();
//creates a file
String content = "My file content";
Files.write(Paths.get("example.txt"),
List.of(content),
StandardCharsets.UTF_8,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
zipper.createZip(new File("example.txt"));
//verifies that the uploadFileToGcsBucket method was called once
mockGcpCloudStorageUtil.verify(()->GcpCloudStorageUtil.uploadFileToGcsBucket(Mockito.any(File.class), Mockito.anyString()), times(1));
//you can insert code here to verify the content of the uploaded file matches the provided file content
//verifies that the file in the temp directory has been deleted
Assert.assertFalse(Files.exists(Paths.get(System.getProperty("java.io.tmpdir")+"example.txt")));
}
@Test(expected = FileNotFoundException.class)
public void testExceptionThrownWhenFileDoesNotExist() throws FxRuntimeException, IOException {
mockGcpCloudStorageUtil.when(() -> GcpCloudStorageUtil.uploadFileToGcsBucket(Mockito.any(File.class), Mockito.anyString())).thenCallRealMethod();
Zipper zipper = new Zipper();
zipper.createZip(new File("doesnt_exist.txt"));
//verifies that the uploadFileToGcsBucket method was not called
mockGcpCloudStorageUtil.verifyNoInteractions();
}
@Test(expected = FxRuntimeException.class)
public void testExceptionThrownWhenIssueGcpUpload() throws IOException, FxRuntimeException {
//this time we force the uploadFileToGcsBucket method to throw an exception
mockGcpCloudStorageUtil.when(() -> GcpCloudStorageUtil.uploadFileToGcsBucket(Mockito.any(File.class), Mockito.anyString())).thenThrow(RuntimeException.class);
Zipper zipper = new Zipper();
//creates a file
String content = "My file content";
Files.write(Paths.get("example.txt"),
List.of(content),
StandardCharsets.UTF_8,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
zipper.createZip(new File("example.txt"));
mockGcpCloudStorageUtil.verify(()->GcpCloudStorageUtil.uploadFileToGcsBucket(Mockito.any(File.class), Mockito.anyString()), times(1));
}
}
我编写了一个接受文件然后创建 zip 文件的方法。一旦 zip 文件创建完成,它就会尝试将其存储在 GCS 存储桶中并从临时目录中删除这些文件。 谁能帮我写一个测试用例。
private void createZip(File file) throws IOException {
File zipFile = new File(System.getProperty("java.io.tmpdir"), Constants.ZIP_FILE_NAME);
if (!file.exists()) {
logger.info("File Not Found For To Do Zip File! Please Provide A File..");
throw new FileNotFoundException("File Not Found For To Do Zip File! Please Provide A File..");
}
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
FileInputStream fis = new FileInputStream(file);) {
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.closeEntry();
}
try {
// store to GCS bucket
GcpCloudStorageUtil.uploadFileToGcsBucket(zipFile, zipFile.getName());
file.delete();
zipFile.delete();
} catch (Exception e) {
logger.error("Exception" + e);
throw new FxRuntimeException("Exception " + e.getMessage());
}
}
作为设计测试用例时的一般经验法则,您既要考虑一切正常时的预期行为,又要考虑可能出错的每种方式的预期行为。
对于您的特定问题,当一切顺利时,您应该期望您的方法压缩作为参数给定的文件,上传它并从临时目录中删除该文件。 您可以通过监视静态 GcpCloudStorageUtil 方法来做到这一点。间谍是 class 的实例,除非指定,否则它们会保留其通常的行为,并且您可以监视哪些方法调用。您可以阅读更多关于 here and here(针对静态方法间谍)的主题。
如果不访问您的其余代码,很难给出一个完整的答案,但我建议:
- 正在创建一个非空文件
- 正在对此文件调用 createZip 方法
- 正在验证是否调用了 GcpCloudStorageUtil.uploadFileToGcsBucket 方法
- 正在验证上传的文件内容是否与您创建的文件匹配
- 正在验证临时目录现在是否为空
还有很多方法可能会出错。例如,作为参数给出的文件可能不存在。您想要编写一个测试用例,以确保在这种情况下抛出 FileNotFoundException。 article 涵盖了使用 JUnit4 或 JUnit5 执行此操作的不同方法。
同样,您可以设计一个测试用例,在其中模拟 GcpCloudStorageUtil.uploadFileToGcsBucket 并强制它抛出异常,然后验证是否抛出了预期的异常。模拟方法意味着强制它以某种方式运行(这里是抛出异常)。同样,您可以阅读有关 here.
主题的更多信息编辑:这是一个可能的测试class。
@SpringBootTest
public class ZipperTest {
MockedStatic<GcpCloudStorageUtil> mockGcpCloudStorageUtil;
@Before
public void init(){
mockGcpCloudStorageUtil = Mockito.mockStatic(GcpCloudStorageUtil.class);
}
@After
public void clean(){
mockGcpCloudStorageUtil.close();
}
@Test
public void testFileIsUploadedAndDeleted() throws IOException, FxRuntimeException {
//mocks the GcpCloudStorageUtil class and ensures it behaves like it normally would
mockGcpCloudStorageUtil.when(() -> GcpCloudStorageUtil.uploadFileToGcsBucket(Mockito.any(File.class), Mockito.anyString())).thenCallRealMethod();
Zipper zipper = new Zipper();
//creates a file
String content = "My file content";
Files.write(Paths.get("example.txt"),
List.of(content),
StandardCharsets.UTF_8,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
zipper.createZip(new File("example.txt"));
//verifies that the uploadFileToGcsBucket method was called once
mockGcpCloudStorageUtil.verify(()->GcpCloudStorageUtil.uploadFileToGcsBucket(Mockito.any(File.class), Mockito.anyString()), times(1));
//you can insert code here to verify the content of the uploaded file matches the provided file content
//verifies that the file in the temp directory has been deleted
Assert.assertFalse(Files.exists(Paths.get(System.getProperty("java.io.tmpdir")+"example.txt")));
}
@Test(expected = FileNotFoundException.class)
public void testExceptionThrownWhenFileDoesNotExist() throws FxRuntimeException, IOException {
mockGcpCloudStorageUtil.when(() -> GcpCloudStorageUtil.uploadFileToGcsBucket(Mockito.any(File.class), Mockito.anyString())).thenCallRealMethod();
Zipper zipper = new Zipper();
zipper.createZip(new File("doesnt_exist.txt"));
//verifies that the uploadFileToGcsBucket method was not called
mockGcpCloudStorageUtil.verifyNoInteractions();
}
@Test(expected = FxRuntimeException.class)
public void testExceptionThrownWhenIssueGcpUpload() throws IOException, FxRuntimeException {
//this time we force the uploadFileToGcsBucket method to throw an exception
mockGcpCloudStorageUtil.when(() -> GcpCloudStorageUtil.uploadFileToGcsBucket(Mockito.any(File.class), Mockito.anyString())).thenThrow(RuntimeException.class);
Zipper zipper = new Zipper();
//creates a file
String content = "My file content";
Files.write(Paths.get("example.txt"),
List.of(content),
StandardCharsets.UTF_8,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
zipper.createZip(new File("example.txt"));
mockGcpCloudStorageUtil.verify(()->GcpCloudStorageUtil.uploadFileToGcsBucket(Mockito.any(File.class), Mockito.anyString()), times(1));
}
}