1

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);

Danilo Tommasina
  • 1,740
  • 11
  • 25

2 Answers2

0

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:

Pratik Joshi
  • 389
  • 4
  • 13
0

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

Priteesh
  • 50
  • 1
  • 1
  • 6