I have this code that works fine.
public class MyClass implements Serializable {
...
private UploadedFile uploadedFile;
public UploadedFile getUploadedFile() {
return uploadedFile;
}
public void setUploadedFile(UploadedFile uploadedFile) {
this.uploadedFile = uploadedFile;
}
public void fileRead(){
...
Scanner scanner = new Scanner(uploadedFile.getInputStream());
while (scanner.hasNextLine()) { ...}
...
}
Now I want to create a test for it. The problem is that when I run the test code below, uploadedFile is null when it gets to the the Scanner line. What do I need to change in the @Test method for uploadedFile not to be null in the Scanner line?
@Test
public void emptyFileTest() throws Exception {
...
UploadedFile uploadedFile = Mockito.mock(UploadedFile.class);
PowerMockito.doReturn(new ByteArrayInputStream("".getBytes())).when(uploadedFile).getInputStream();
this.myClass.fileRead();
...
}
I also tried this, but with the same results.
PowerMockito.when(uploadedFile.getInputStream()).thenReturn(new ByteArrayInputStream("".getBytes()));
CodePudding user response:
Doesn't look like you set the uploadedFile variable in myClass
PowerMockito.doReturn(new ByteArrayInputStream("".getBytes())).when(uploadedFile).getInputStream();
You can do the same a bit easier: new ByteArrayInputStream(new byte[0])
. There is no need to use a string to create an empty byte array.