Reputation: 140
I have a java method checking File Existence..
public String checkFileExistance(String arg) throws IOException {
String FolderPath = SomePath
File file = new File(FolderPath);
if (file.exists() && file.isDirectory()) {
//Do something here
}
}
i want to mock the file.exist() and file.isDirectory() to make it return true always
i tried below method:
public void test_checkFileExistance1() throws IOException {
/**Mock*/
File mockedFile = Mockito.mock(File.class);
Mockito.when(mockedFile.exists()).thenReturn(true);
Mockito.when(mockedFile.isDirectory()).thenReturn(true);
/**Actual Call*/
ProcessClass.checkFileExistance("arg");
}
but it always returns false
Upvotes: 3
Views: 11600
Reputation: 3618
You mock a File
, but that is not the one that is used in your class. In your class you call new File(...)
which returns a real File
Object
; not the one you've prepared.
You can use PowerMockito to do this.
Something along the lines of:
@RunWith(PowerMockRunner.class)
@PrepareForTest(TheClassWithTheCheckFileExistanceMethod.class)
public class TheTest {
@Before
public void setup() {
final File mockFile = mock(File.class);
Mockito.doReturn(true).when(mockFile).exists();
// Whatever other mockery you need.
PowerMockito.whenNew(File.class).withAnyArguments()
.thenReturn(mockFile);
}
}
will do this.
Upvotes: 1
Reputation: 3059
You create a mock object mockedFile
in your test method. But this mock object is not used within your checkExistance()
method. This is because you create another File object and call the exists()
and isDirectory()
methods on this newly created (and not mocked object).
If your checkExistance()
method would take a file object as parameter instead of the name of the file, you could pass the mocked object to the method and it would work as expected:
public String checkFileExistance(File file) throws IOException {
if (file.exists() && file.isDirectory()) {
// do something here
}
}
public void test_checkFileExistance1() throws IOException {
File mockedFile = Mockito.mock(File.class);
Mockito.when(mockedFile.exists()).thenReturn(true);
Mockito.when(mockedFile.isDirectory()).thenReturn(true);
/**Actual Call*/
ProcessClass.checkFileExistance(mockedFile);
}
Upvotes: 1