java - 如何使用 Json 对象进行模拟
问题描述
我写了一个非常简单的类,其中有一个方法采用 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
. 您真正想要做的是返回给定jsonArray
的任何调用,someService.getJsonArray
第二个参数是“教育”。您可以通过使用 Mockito 匹配器来做到这一点,例如anyObject
or anyString
:
when(someservice.getJsonArray(any(), anyString())).thenReturn(jsonArray);
如果您想模拟更具体的方法调用,ecudations
或者content
您也可以为第二个参数提供匹配器:
when(someservice.getJsonArray(any(), eq("educations"))).thenReturn(jsonArray);
注意:为此,someService
需要模拟。具体过程取决于您使用的框架,例如在您的测试类中,您执行类似的操作
@Mock
private SomeService someService;
@BeforeMethod
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
有关更多示例,请参见https://dzone.com/articles/use-mockito-mock-autowired
推荐阅读
- apache-spark - Spark Shuffle 写入大小是输入大小的 7500 倍
- javascript - 无法访问模块函数中的 quill 实例
- postgresql - 与触发函数和插入语句sql有关的错误
- python - Python中的多个窗口,tkinter
- 3d - 使用 Python 创建 3D EEG 地形图
- python - 一定半径内分组 GPS 数据的平均值
- powerbi - Expression.Error:无法识别名称“DIVIDE”。确保拼写正确
- google-analytics - GA4 等效获取 > 广告系列 > 自然关键字 > 着陆页
- javascript - Frontity 错误中的矿物 UI 情感
- cocoapods - 我自己的 pod 库没有在项目中导入