【问题标题】:How to assert Userdefined Exceptions in JUNIT4.7如何在 JUNIT4.7 中断言用户定义的异常
【发布时间】:2015-11-19 15:24:23
【问题描述】:

我正在使用 JUNIT 4.7 和 maven

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.7</version>
    </dependency>

我有上传文件的方法,我正在使用我自己的用户定义的异常,如下所示

public void uploadFile(String fileName) {
    File file  = null;

    try {
        file = new File(DIR + "/" + fileName);

        // If the file size exceeds 10 MB raise an exception
        if ((file.length() / MB) > 10)
            throw new FileSizeExceedLimitException("File size should not exceed 10 MB");

        else {
            System.out.println("File Uploaded Successfully");
        }
    } catch (FileSizeExceedLimitException e) {
        e.printStackTrace();
    }
}

我的用户定义的异常如下所示

public class FileSizeExceedLimitException extends Exception{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public FileSizeExceedLimitException(String s){
        super(s);
    }
}

我的测试用例如下所示

方法一:

DocxOperations operations = null;

@Rule
public final ExpectedException exception = ExpectedException.none();

@Before
public void before() {
    operations = new DocxOperations();
}

@Test
public void testUploadFileSize() {
    exception.expect(FileSizeExceedLimitException.class);
    operations.uploadFile("Bigdata.docx");
}

方法二:

@Test(expected = FileFormatException.class)
public void testUploadFile() {
    operations.uploadFile("01 Big Data Hadoop Intro V 2.0.docx");
}

方法三:

@Test(expected = FileFormatException.class)
public void testUploadFile() throws FileFormatException{
    operations.uploadFile("01 Big Data Hadoop Intro V 2.0.docx");
}

在上述所有方法中,我都无法通过测试用例,我已经看到了这些解决方案,但它们对我没有用

Assert Exception, Testing Exception

在我的主要代码中,即uploadFile 方法中,我只能使用trycatch 不是throws

【问题讨论】:

    标签: java maven unit-testing junit4


    【解决方案1】:

    问题是您没有在方法调用之外抛出异常:

    这是简化的代码,只有 throw 和 catch 可以更清楚地看到它

    try {
       ...
    
            throw new FileSizeExceedLimitException("File size should not exceed 10 MB");
        ...
    
      } catch (FileSizeExceedLimitException e) {
        e.printStackTrace();
    }
    

    您正在捕获并吞下异常。删除 try-catch 并使您的方法 throws FileSizeExceedLimitException 并且测试应该可以工作

    【讨论】:

    • 感谢您的回答,但在我的主要代码中,即uploadFile 方法中,我只能使用trycatch 而不是throws
    猜你喜欢
    • 2023-04-06
    • 2019-10-27
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2011-05-02
    • 2020-03-22
    • 2018-11-21
    • 2021-11-21
    相关资源
    最近更新 更多