【发布时间】:2020-09-11 21:43:03
【问题描述】:
我正在尝试在 Android Studio 中创建单元测试,当我调用函数 presenter.getImageFile() 时,它显示 NullPointerException
@Test
public void shouldCallForErrorWhenImageFileIsNull() throws IOException {
when(presenter.getImageFile()).thenReturn(null);
presenter.captureImage();
verify(view).cameraImageFileError();
}
上面的代码来自我的测试文件,下面的代码来自我的 Presenter 类的部分。
@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;
}
执行上述代码时出现以下错误:
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)
这里 MainActivity Presenter 中的第 76 行是: File imageFile = File.createTempFile(imageName, ".jpg", storageDir); 我的 UnitTest 中的第 49 行是:when(presenter.getImageFile()).thenReturn(null);
【问题讨论】:
标签: java android junit android-testing