简体   繁体   中英

Error while trying to use when and thenReturn in JUnit Testing and Mockito (NullPointerException)

I am trying to create Unit tests in Android Studio, and when I am calling the function presenter.getImageFile(), it is showing NullPointerException

@Test
public void shouldCallForErrorWhenImageFileIsNull() throws IOException {
    when(presenter.getImageFile()).thenReturn(null);
    presenter.captureImage();

    verify(view).cameraImageFileError();

}

The above code is from my Test File, and the below code is from the section of my Presenter class.

@Override
public File getImageFile() throws IOException {
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
    String imageName = "jpg_" + timeStamp + "_";

    File imageFile = File.createTempFile(imageName, ".jpg", storageDir);

    setPrevImagePath(getCurrentImagePath());
    setCurrentImagePath(imageFile.getAbsolutePath());
    Log.d("MainActivity#FilePath", imageFile.getAbsolutePath());

    return imageFile;
}

When executing the above code I am getting the following error:

java.lang.NullPointerException
    at java.io.File.<init>(File.java:363)
    at java.io.File$TempDirectory.generateFile(File.java:1916)
    at java.io.File.createTempFile(File.java:2010)
    at com.example.imagepicker.presenter.MainActivityPresenter.getImageFile(MainActivityPresenter.java:76)
    at com.example.imagepicker.ExampleUnitTest.shouldCallForErrorWhenImageFileIsNull(ExampleUnitTest.java:49)

Here Line 76 in MainActivity Presenter is: File imageFile = File.createTempFile(imageName, ".jpg", storageDir); And Line 49 in my UnitTest is: when(presenter.getImageFile()).thenReturn(null);

If you are trying to mock an entire method of the class you are testing, then you may make use of PowerMockito with Spy classes. Here are some examples:

The issue here is that you are trying to mock the behavious of a method of the class you are testing. You will need to spy the class for doing it and not mock.

Just Add @Spy annotation above the presenter class initialization in the textClass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM