java - 模拟 toURI() 方法时出现 AssertionFailedError

标签 java unit-testing exception mockito

我正在尝试 mock toURI()方法来自FileObject.java类(该类属于 org.openide.filesystems 包)。

方法声明如下:

public final URI toURI() {
    // Compiled code
}

到目前为止,我有这个测试代码:

@Test
public void test() throws Exception {
    String myUrl = "http://stackoverflow.com";
    URI myURI = new URI(myUrl);
    FileObject mocked = Mockito.mock(FileObject.class);

    Mockito.when(mocked.toURI()).thenReturn(myURI);

    assertEquals(myURI, mocked.toURI());
}

但是,当我运行测试时,它在 Mockito.when(mocked.toURI()).thenReturn(myURI); 行中崩溃。出现以下错误:

Testcase: test(myapp.logicLayer.LogicTest): FAILED File object Mock for FileObject, hashCode: 443290224 returns null from getFileSystem() junit.framework.AssertionFailedError: File object Mock for FileObject, hashCode: 443290224 returns null from getFileSystem()

我尝试了多种解决方法,但找不到任何有效的方法。

我什至尝试使用PowerMockito.stub(PowerMockito.method(FileObject.class, "toURI")).toReturn(myURI); ,但我得到了同样的错误,更不用说这应该在静态方法中使用,但事实并非如此。

我正在使用 Mockito 1.10.19。我用 google 搜索了一下,发现只有 Mockito 的第 2 版能够模拟 final方法。我的猜测是这可能是问题所在,但我真的不确定。

编辑:刚刚使用 Mockito 2.8.9 进行测试,问题仍然存在。

有人知道这里出了什么问题吗?

最佳答案

发生此问题是因为这是 final方法

从 Mockito 2.1.0 开始,可以模拟 final方法/类。来自 Mockito documentation :

For a long time our users suffered a disbelief when Mockito refused to mock a final class. Mocking of final methods was even more problematic, causing surprising behavior of the framework and generating angry troubleshooting. The lack of mocking finals was a chief limitation of Mockito since its inception in 2007 (...) it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker

为了实现 final方法模拟,您应该创建包含单行的文件src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker:

模拟制作者内联

mockito 将能够模拟 final方法。

关于java - 模拟 toURI() 方法时出现 AssertionFailedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52100653/

相关文章:

java - 使用 Hibernate for ORM 的抽象/具体类的 MySQL 表

java - Swing 中的表格单元格编辑代码给出错误的输出

java - 如何使用spring的MockMultipartHttpServletRequest?获取 "no multipart boundary was found"

python - 为什么嵌套时不添加函数的速度测试? (Python)

java - Bufferedreader 关闭后,Inputstream 也应该关闭吗?

Java 到 Objective-C RSA 实现

python - 运行单元测试时如何修补或修改函数内部的列表?

android - 无法在 21 以下的 Api 中获取提供商 com.google.firebase.provider.FirebaseInitProvider

java - PhoneGap android : getting cannot create handler inside thread that has not called Looper. 准备()

python - 即使通过代理的连接失败,如何重试当前循环