首页 > 解决方案 > 如何使用 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);

标签: javamockito

解决方案


在您的代码中,您定义当jsonObject遇到的特定实例时,被模拟的someservice应该返回jsonArray. 您真正想要做的是返回给定jsonArray的任何调用,someService.getJsonArray第二个参数是“教育”。您可以通过使用 Mockito 匹配器来做到这一点,例如anyObjector 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


推荐阅读