gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:49:06 25 4
gpt4 key购买 nike

我正在尝试 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com