3

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.

Vinay Pandey
  • 1,129
  • 3
  • 16
  • 33

1 Answers1

2

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);
LeTex
  • 1,452
  • 1
  • 14
  • 28