Learnt JUnit yesterday, learning Mockito today
I wrote a simple class;
public class FileOperations {
public boolean autoMove(){
List<byte[]> patterns = getListofPatterns();
for(byte[] pattern: patterns){
System.out.println(new String(pattern));
if(seekInHeader(pattern)){
//logic to move file of specific folder of specific extension
return true;
}
}
return false;
}
public boolean seekInHeader(byte[] pattern){
return false;
}
public List<byte[]> getListofPatterns(){
return null;
}
}
And trying to test it as follows
@Test
public void autoMoveTest(){
FileOperations fo = mock(FileOperations.class);//stub
List<byte[]> dummyPatterns = new ArrayList<byte[]>();//specify stub value
dummyPatterns.add("amit".getBytes());
when(fo.getListofPatterns()).thenReturn(dummyPatterns);
when(fo.seekInHeader(anyString().getBytes())).thenReturn(true);
System.out.println(new String(fo.getListofPatterns().get(0)));
System.out.println(fo.seekInHeader("amit".getBytes()));
System.out.println(fo.autoMove());
assertTrue(fo.autoMove());
}
Output:
amit
true
false
As I set seekHeader() to return true. Why fo.autoMove() is returning false?
You can do it using spy as follows;
Why your code is failing
Because you were not stubbing
fo.autoMove(). When you call a real method with mocked object, actual method never runs. It just returns default value of return-type or stubbed value. So even if you returntruefromautoMove(), it will return false for a mock object.