我使用maven
使用JUNIT 4.7 <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);
}
}
我的测试用例如下所示
方法1:
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");
}
方法2:
@Test(expected = FileFormatException.class)
public void testUploadFile() {
operations.uploadFile("01 Big Data Hadoop Intro V 2.0.docx");
}
方法3:
@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
方法中,我只能使用try
,catch
不是throws
答案 0 :(得分:1)
问题是你没有抛出超出方法调用的异常:
这是简化的代码,只有throw和catch才能更清楚地看到它
try {
...
throw new FileSizeExceedLimitException("File size should not exceed 10 MB");
...
} catch (FileSizeExceedLimitException e) {
e.printStackTrace();
}
你正在捕捉并吞下这个例外。删除try-catch并使您的方法throws FileSizeExceedLimitException
并且测试应该正常工作