簡體   English   中英

用於在 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());
    }

}

作為設計測試用例時的一般經驗法則,您既要考慮一切正常時的預期行為,又要考慮事情可能出錯的每種方式的預期行為。

對於您的特定問題,當一切正常時,您應該期望您的方法壓縮作為參數給出的文件,上傳它並從臨時目錄中刪除文件。 您可以通過監視您的 static GcpCloudStorageUtil 方法來做到這一點。 間諜是 class 的實例,除非指定並且您可以監視哪些方法調用,否則它們會保留其通常的行為。 您可以在此處此處閱讀有關該主題的更多信息(對於 static 方法間諜)。

如果不訪問您的代碼的 rest,很難給出徹底的答案,但我建議:

  • 創建一個非空文件
  • 對此文件調用 createZip 方法
  • 驗證是否調用了 GcpCloudStorageUtil.uploadFileToGcsBucket 方法
  • 驗證上傳的文件內容是否與您創建的文件匹配
  • 驗證臨時目錄現在是否為空

還有一些方法可以使 go 出錯。 例如,作為參數給出的文件可能不存在。 您想編寫一個測試用例,以確保在這種情況下拋出 FileNotFoundException。 本文介紹了使用 JUnit4 或 JUnit5 執行此操作的不同方法。

同樣,您可以設計一個測試用例,在其中模擬 GcpCloudStorageUtil.uploadFileToGcsBucket 並強制它拋出異常,然后驗證是否拋出了預期的異常。 Mocking 方法意味着強制它以某種方式運行(這里,拋出異常)。 同樣,您可以在此處閱讀有關該主題的更多信息。

編輯:這是一個可能的測試 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));

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM