【问题标题】:Error while trying to use when and thenReturn in JUnit Testing and Mockito (NullPointerException)尝试在 JUnit 测试和 Mockito 中使用 when 和 thenReturn 时出错(NullPointerException)
【发布时间】: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


    【解决方案1】:

    这里的问题是您试图模拟您正在测试的类的方法的行为。你需要监视类来做这件事,而不是模拟。

    只需在textClass中的presenter类初始化上方添加@Spy注解

    【讨论】:

      【解决方案2】:

      如果您尝试模拟您正在测试的类的整个方法,那么您可以将 PowerMockito 与 Spy 类一起使用。以下是一些示例:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-10
        • 1970-01-01
        相关资源
        最近更新 更多