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

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.