gpt4 book ai didi

java - 如何使用 Json 对象进行模拟

转载 作者:行者123 更新时间:2023-12-02 08:54:22 25 4
gpt4 key购买 nike

我编写了一个非常简单的类,其中有一个方法采用 Json 字符串,然后处理不同的值。为此,有一个辅助类也可以根据键提取 JsonArray 和 JsonObject。功能工作正常,但是当我尝试编写单元测试时,它并不符合我的预期。这是代码:

public class Test{

@Autowired
private SomeServices someservice;

public Person convertJsonToPerson(String json) {

String content = (String) new JSONObject(json).get("content");
JSONObject talentJson = new JSONObject(content);

getEductionDetail(talentJson);
getContectDetail(talentJson)
}

private JSONArray getEductionDetail(JSONObject jsonObject) {
return someservice.getJsonArray(jsonObject, "educations");

}

private JSONArray getContectDetail(JSONObject jsonObject) {
return someservice.getJsonArray(jsonObject, "educations");

}
}

正如这里所看到的,我有两种方法来提取 json 对象,但实际上类有 20 个用于不同目的的方法。

这是对此的测试用例。

@Test
public void test() throws IOException {

String json = util.readFile("data.json").trim();
JSONObject jsonOject = new JSONObject(talentJson);

JSONObject edu = new JSONObject();
edu.put("school", "St. Marry");
edu.put("degree", "Master");

JSONArray jsonArray = new JSONArray();
jsonArray.put(0, edu);

when(someservice.getJsonArray(jsonOject, "educations")).thenReturn(jsonArray);
assertNotNull(convertJsonToPerson(json));
}

以下行不起作用。我认为测试中的 jsonObject 和实际代码是不同的,这就是 id 不匹配的原因。有人可以帮我解决这个问题吗?如何基于对象的模拟。

when(someservice.getJsonArray(jsonOject, "educations")).thenReturn(jsonArray);

最佳答案

在您的代码中,您定义当遇到 jsonObject 的特定实例时,模拟的 someservice 应返回 jsonArray。您真正想要做的是,为任何对 someService.getJsonArray 的调用返回给定的 jsonArray ,第二个参数是“educations”。您可以使用 Mockito 匹配器(例如 anyObjectanyString)来完成此操作:

when(someservice.getJsonArray(any(), anyString())).thenReturn(jsonArray);

如果您想使用 ecudationscontent 模拟更具体的方法调用,您也可以为第二个参数提供匹配器:

when(someservice.getJsonArray(any(), eq("educations"))).thenReturn(jsonArray);

注意:要使其工作,需要模拟 someService。具体过程取决于您使用的框架,例如。 G。在你的测试类中你做了类似的事情

@Mock
private SomeService someService;

@BeforeMethod
public void initMocks() {
MockitoAnnotations.initMocks(this);
}

有关更多示例,请参阅 https://dzone.com/articles/use-mockito-mock-autowired

关于java - 如何使用 Json 对象进行模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60578227/

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