【发布时间】:2017-03-06 21:35:38
【问题描述】:
我有一个 get file 方法,如果提供给该方法的路径存在,它会给出一个文件。如果文件不存在,它将抛出NullPointerException。
public File getFile(String downloadFileName) throws Exception {
File fileToUpload = new File(getFileLocation(downloadFileName));
if(!fileToUpload.exists() && !fileToUpload.isFile()){
throw new Exception("File not found");
}
return fileToUpload;
}
我想编写一个Junit 测试来检查该方法是否在文件不存在并且路径不是文件而是目录(if 循环中涵盖的条件)时抛出异常。
朱尼特:
public class KnewtonContentInventoryWokerTest {
private HttpWorker httpHelper = mock(HttpWorker.class);
private KnewtonContentInventoryWorker knewtonContentInventoryHelper;
private MessageHandler messageHandler = spy(new MessageHandler(false));
private String programNameString = "Realize Sample Program";
private String completeResponse;
private String filePath = "src/test/resources/Content_Inventory_testFile.xls" ;
private String fileName = "Content_Inventory_testFile";
private String fileDir = "src/test/resources/";
private String jobIdRestPath = "";
private String jobStatusRestPath = "";
private String downloadExcelFileRestPath = "";
private String uploadFileToS3RestPath = "";
private File file = new File(filePath);
@Before
public void setup() throws Exception {
setupWorker();
}
@Before
public void setupWorker() {
AuthContext authContext = new AuthContext();
authContext.setAuthenticationDetails("/test/", "user", "pass", new HashSet<Cookie>());
File file = new File("src/test/resources/Content_Inventory_testFile.xls");
knewtonContentInventoryHelper = spy(new KnewtonContentInventoryWorker(authContext,programNameString, externalIds));
knewtonContentInventoryHelper.messageHandler = messageHandler;
}
/**
* Test the setting up method
*/
@Test(expected = Exception.class)
public void testGetFileThrowsException() throws Exception {
doThrow(new Exception("")).when(knewtonContentInventoryHelper).getFile(anyString());
knewtonContentInventoryHelper.getFile(anyString());
}
}
上面的Junit 是我现在所拥有的,但是我认为我没有做正确的测试。
我无法理解如何在测试方法testGetFileThrowsException() 中测试这两个场景。如果文件不存在或文件路径是目录,我希望抛出异常。
【问题讨论】: