Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any way to test/mock a File input using junit?

I am trying to test the following code without using a real xls file...

File file = new File("file.xls");
final FileInputStream input = new FileInputStream(file);

My problem is that I cannot create an instance of File, and I dont know how to simulate I am creating a new file and how to mock what to expect.

Is there any way to do this using junit?

Thanks

like image 490
jpganz18 Avatar asked Nov 09 '22 02:11

jpganz18


1 Answers

Yes, there are a couple different ways.

You can use something like Powermock to intercept the call to new. See this other answer where I explain how to do that in detail EasyMock - mock object returned from new Object

Do you actually want the bytes from the excel file or an "excel object"? It might be worth refactoring to pass around a Workbook object or whatever you are using to parse the excel downstream and then use dependency injection. Your test can then inject a mock Workbook object instead of a real file.

like image 200
dkatzel Avatar answered Nov 14 '22 23:11

dkatzel