首页 > 解决方案 > 如何为采用文件路径并创建新文件的方法编写 Junit 测试?

问题描述

我在 Java 类中有一个方法,它采用文件路径并创建一个新文件。如何为此方法编写 Junit 测试?

public String sendToECM(String filePath) {
    String ecmDocId = StringUtils.EMPTY;

    try {
        File file = new File(filePath);
        if(file.exists()) {
            DocumentPropertiesVO documentPropertiesVO = UploadFileToContentManagement.uploadDocument(file);
            ecmDocId = documentPropertiesVO.getDocumentID();
        }
        return ecmDocId;
    } catch (SomeException cee) {
        log.error("There was an error adding the document", cee);
    }
}

标签: javaunit-testingjunitmockito

解决方案


@Test
void testValidFilePath() {
  String filePath = "path.txt";
  String str = sendToECM(filePath);
  Assertions.assertNotEquals(str, ""); // or null, depending on what your StringUtils.EMPTY is doing

@Test
void testInvalidFilePath() {
  String filePath = "invalidPath.txt";
  String str = sendtoECM(filePath);
  Assertions.assertEquals(str, StringUtils.EMPTY);

推荐阅读