Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock variables in try-with-resource blocks [duplicate]

I am currently using junit-4.12 along with mockito-1.10. I am trying to inject mocks into try-with-resource block such as

try (InputStream inputStream = new FileInputStream("inputFile.txt") {
    ...
}

Is there a way in which I can inject mock for inputStream? I have tried declaring inputStream outside of try block as below:

InputStream inputStream;
try (inputStream = new FileInputStream("inputFile.txt") {
    ...
}

However, Java does not like this and throws error.

I am open to using any other library if I must, any help will be appreciated!

Thanks.

like image 844
Vinay Pandey Avatar asked Sep 06 '25 03:09

Vinay Pandey


1 Answers

This should do it:

using PowerMockito

import static org.powermock.api.mockito.PowerMockito.whenNew;

 // ...
InputStream inputStreamMock = mock(InputStream.class);
whenNew(FileInputStream.class).withArguments("inputFile.txt").thenReturn(inputStreamMock);
like image 104
LeTex Avatar answered Sep 07 '25 23:09

LeTex