gpt4 book ai didi

java - 是否可以仅在第一次出现时使用 "PowerMockito.whenNew()"?

转载 作者:行者123 更新时间:2023-11-30 08:08:33 26 4
gpt4 key购买 nike

我即将构建一个 JSON 对象并想要测试结果。我正在调用一个公共(public)方法。有几个私有(private)方法并进行递归调用。在开始的某个地方我有这个:

JSONObject obj = new JSONObject();

这是我的“根”对象。不幸的是,它没有作为参数等给出,而是使用构造函数创建,如图所示。在 recursvie 调用中,此构造函数会被多次调用以构建结构。我需要的是测试中断言的根对象。

所以我试图以某种方式得到它,并在这里尝试了这种方法......以下代码:

JSONObject json = new JSONObject();
PowerMockito.whenNew(JSONObject.class).withNoArguments().thenReturn(json);

[...]

assertThat(json.get("bla"), is("hello")); // assertions possible to my root json object

这将允许我在执行断言后建立根 json 对象。但我遇到了 stackoverflow 异常。为什么?因为递归调用的构造函数现在传递了我的根对象,而不是调用构造函数。

底线是,我在这里需要什么:我想说“whenNew(JSONObject.class, times(1))”或类似的东西。这样只有第一个构造函数调用会被模拟,而后面的则不再被模拟。我认为这应该是可能的,但找不到实现此目标的方法:(

感谢大家的帮助!

最佳答案

我也遇到了同样的问题。我有一个主要的 JSONObject 和一些内部 JSONObject,但我只想要第一个,其他的可以照常工作。基本上,您也必须在第一次之后设置实例。

final JSONObject requestJSON = new JSONObject();
final JSONObject innerJSONExample = new JSONObject();
final JSONObject anotherInnerJSONExample = new JSONObject();

PowerMockito.whenNew(JSONObject.class).withNoArguments()
.thenReturn(requestJSON) //first return
.thenReturn(innerJSONExample) //second return
.thenReturn(anotherInnerJSONExample); //third return and so on...
//I will not use innerJSONExample and the other, but this is needed

值得一提的是,您必须在BEFOREwhenNew之前创建实例。另外,您不能这样做:

PowerMockito.whenNew(JSONObject.class).withNoArguments()
.thenReturn(requestJSON) //first return
.thenReturn(new JSONObject()); //second return

因为您已经设置了当“new JSONObject()”返回“requestJSON”时,那么,当您执行此操作时,您将返回相同的< em>“requestJSON”,你可能会得到StackOverflowError

关于java - 是否可以仅在第一次出现时使用 "PowerMockito.whenNew()"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30736035/

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