[英]How to test File.delete() function in Junit
我有一種如下所示的方法:
public final class someTask {
public void sampleMethod(String filePath) {
//It is calling Files.delete() method.
Files.delete(new File(filePath).toPath)
}
}
當我測試上述方法(例如該文件中的ValidRecord,是否使用有效文件參數等)測試用例時,大多數情況下我的測試用例都失敗了。 請有人可以幫助我如何測試上述情況。
要獲取文件,我正在使用以下代碼段
@Mock
File fileMock;
@Rule
ExpectedException exception = ExpectedException.none();
PowerMockito.whenNew(File.class).withArguments(VALID_Path).thenReturn(fileMock);
PowerMockito.when(fileMock.exists()).thenReturn(true);
PowerMockito.when(fileMock.isFile()).thenReturn(true);
在這種情況下,我不打算測試Files.deplete()方法,但是我計划自己的方法的測試行為。 在此過程中,即使我創建臨時文件,每次遇到“ java.nio.file.NoSuchFileException”異常也是如此。
請一些可以提供示例,如何測試。
有人可能會辯解說,通過模擬和交互來驗證行為是錯誤的。 我會做以下
在本地文件系統上創建一個臨時文件
調用方法sampleMethod
解決此類問題的一種有價值的方法是退后一步批評您的應用程序設計。 問問自己,是否有設計問題,尤其是當您覺得測試代碼似乎有點困難時。
的確如此: 您可以/應該改進軟件的設計!
讓我們從您的課程開始(順便說一句,我將名稱更改為駱駝外殼):
public final class SomeTask {
public void sampleMethod(String filePath) {
Files.delete(new File(filePath).toPath);
}
}
我將忽略異常。 另外,您在代碼中的某處正在使用此類:
SomeTask task = new SomeTask();
String filePath = ...
task.sampleMethod(filePath);
首先要意識到的是:在類SomeTask
您對文件刪除功能具有依賴性。 使此依賴性可見!
但是,你是怎么做的? 使用界面:
@FunctionalInterface
public interface FileDeletor {
void delete(String filePath);
}
現在,您可以通過添加此類刪除器的字段來更改班級:
public final class SomeTask {
private final FileDeletor deletor;
public SomeTask(FileDeletor deletor) {
this.deletor = Objects.requireNonNull(deletor);
}
public void sampleMethod(String filePath) {
deletor.delete(filePath);
}
}
使用這種方法,您可以將文件刪除的技術工作委托給另一個現在必須實現該接口的類(如下所示)。 這也使您的班級更加連貫,因為它現在可以專注於自己的功能。
現在,我們需要一個實現該接口的類:
public final class DefaultFileDeletor implements FileDeletor {
@Override
public void delete(String filePath) {
Files.delete(new File(filePath).toPath());
}
}
注意,這里我仍然忽略異常。 現在我們還必須更改使用方:
FileDeletor deletor = new DefaultFileDeletor();
SomeTask task = new SomeTask(deletor);
String filePath = ...
task.sampleMethod(filePath);
使用這種方法,您還可以通過Spring自動裝配或類似的依賴項注入框架來構建應用程序。
讓我們繼續進行測試。 如果願意,還可以測試新類DefaultFileDeletor
。 但是您知道它僅使用JDK功能,該功能本身已經過足夠的測試。 無需測試這個簡單的類。
但是,現在如何測試類SampleTask
? 首先,僅出於測試目的,您需要接口的實現:
public class FileDeletorForTestPurposes implements FileDeletor {
private String filePath;
private boolean deleted;
@Override
public void delete(String filePath) {
this.filePath = filePath;
deleted = true;
}
public String getFilePath() {
return filePath;
}
public boolean isDeleted() {
return deleted;
}
}
現在,您可以測試代碼了:
FileDeletorForTestPurposes deletor = new FileDeletorForTestPurposes();
SomeTask task = new SomeTask(deletor);
String filePath = ...
task.someMethod(filePath);
assertEquals(filePath, deletor.getFilePath());
assertEquals(true, deletor.isDeleted());
現在,您還可以簡單地創建FileDeletor
模擬,並通過表達對它的期望來使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.