I have the following classes
class FileDownloader {
public static void downloadFile(String repoUrl, String filename) throws IOException {
// Downloads file from internet
}
}
class FileDownloaderAndProcessor {
public static void downloadAndProcessFile() throws IOException {
//run some processing to figure out what to download
FileDownloader.downloadFile(a, b);
//run various processing on downloaded file
}
}
I used to mock FileDownloader with PowerMockito.doAnswer, where I could basically mock the downloadFiles function by copying a local file from one place to another to simulate the download, then run various tests on the postproccessing
PowerMockito.doAnswer(invocation -> {
//copy from local location x to y depending on arguments
}.when(FileDownloader.class, "downloadFile").etc etc
Due to a recent spring upgrade, we can no longer use powermock and are migrating to MockedStatic. However, I don't see the doAnswer functionality in MockedStatic. I really don't want the tests to require an internet connection to run. How do I mock this void method?
Mockito version: org.mockito:mockito-core:jar:4.0.0 org.mockito:mockito-inline:jar:4.0.0
CodePudding user response:
You can try when...thenAnswer...
on MockedStatic
provided by Mockito.
try (MockedStatic<FileDownloader> mockedFileDownloader = Mockito.mockStatic(FileDownloader.class)) {
mockedFileDownloader.when(() -> mockedFileDownloader.downloadFile(repoUrl, filename))
.thenAnswer(invocation -> {
// copy from local location x to y depending on arguments
return null;
});
}
CodePudding user response:
Since all your static classes seem to have only one method you can simply mock the entire class.
Mockito.mockStatic(FileDownloader.class, invocationOnMock -> {
System.out.println("Do Something that simulates the download");
return null;
});
FileDownloader.downloadFile("someRepo", "someFile");