如何在mockito嘲笑Gson

wixjitnu  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(221)

在我的申请中,在为上述方法编写单元测试时,我无法模拟Gson类,因为它是一个final类。在互联网上做一些研究时,我发现应该在src/test/resources/mockito-extensions上创建一个名为org.mockito.plugins.MockMaker的文件,其内容如下所示,

mock-maker-inline

但是我仍然不能让它工作。我做错了什么。
我在运行上述测试用例时遇到以下异常(由于gson对象未被正确模拟)

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1

    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
    at com.google.gson.Gson.fromJson(Gson.java:803)
    at com.google.gson.Gson.fromJson(Gson.java:768)
    at com.google.gson.Gson.fromJson(Gson.java:717)
    at com.google.gson.Gson.fromJson(Gson.java:689)
    at org.kasun.sample.client.supportjira.impl.GroupRestClientImpl.addUser(GroupRestClientImpl.java:104)
    at org.kasun.sample.client.GroupRestClientImplTest.addUserToAGroup(GroupRestClientImplTest.java:102

请按以下方式查找我类,
已测试的类别:

import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import org.testing.kasun.client.supportjira.dto.SaveResult;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

  public class GroupRestClientImpl{
    private Gson gson = new Gson();

    @Override
    public SaveResult addUser(User user, Group group) {

        WebResource resource = client.resource(baseUri + "/" + GROUP_URI_PREFIX + "/user?groupname=" + group.getName());
        ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
                .post(ClientResponse.class, user);

        String jsonText;
        if (response.getStatus() != Response.Status.CREATED.getStatusCode()) {
            jsonText = response.getEntity(String.class);
            JiraError jiraError = gson.fromJson(jsonText, JiraError.class);
            throw new JiraException(jiraError.toString());
        }
        jsonText = response.getEntity(String.class);
        SaveResult saveResults = gson.fromJson(jsonText, SaveResult.class);
        return saveResults;
    }

}

测试类别:

class TestBase {

static final String JIRA_API_URL = "http://www.jira.com/jira/rest/api/2";
static final String MEDIA_TYPE_JSON = MediaType.APPLICATION_JSON;

@Mock
Client client;

@Mock
WebResource webResource;

@Mock
WebResource.Builder webResourceBuilder;

@Mock
ClientResponse clientResponse;

@Mock
Gson gson;

void setupMocks(Class<?> postPayloadType) {

    initMocks(this);
    when(client.resource(anyString())).thenReturn(webResource);
    when(webResource.accept(anyString())).thenReturn(webResourceBuilder);
    when(webResourceBuilder.type(anyString())).thenReturn(webResourceBuilder);
    when(webResourceBuilder.get(eq(ClientResponse.class))).thenReturn(clientResponse);
    when(webResourceBuilder.post(eq(ClientResponse.class), any(postPayloadType))).thenReturn(clientResponse);
    when(clientResponse.getEntity(eq(String.class))).thenReturn("responseText");
}

@AfterMethod
protected void clearMocks() {

    reset(client);
    reset(webResource);
    reset(webResourceBuilder);
    reset(clientResponse);
    reset(gson);
}

}

public class GroupRestClientImplTest extends TestBase {

    private static final String JIRA_GROUP_API_URL = JIRA_API_URL + "/group";
    private static final String JIRA_GROUP_MEMBER_API_URL = JIRA_GROUP_API_URL + "/member?groupname=";
    private static final String JIRA_GROUP_MEMBER_ADD_API_URL = JIRA_GROUP_API_URL + "/user?groupname=";

    private GroupRestClient groupRestClient;

    @BeforeMethod
    public void initialize() throws URISyntaxException {

        super.setupMocks(Group.class);
        groupRestClient = new GroupRestClientImpl(new URI(JIRA_API_URL), client);
    }

   @Test
    public void addUserToAGroup() throws URISyntaxException {

        when(clientResponse.getStatus()).thenReturn(Response.Status.CREATED.getStatusCode());
        when(webResourceBuilder.post(eq(ClientResponse.class), any(User.class))).thenReturn(clientResponse);
        SaveResult saveResult = new SaveResult();
        when(gson.fromJson(anyString(), isA(SaveResult.class.getClass()))).thenReturn(saveResult);
//        when(gson.fromJson(anyString(), eq(SaveResult.class))).thenReturn(saveResult);

        User user = new User();
        Group group = new Group();
        group.setName("group");
        SaveResult result = groupRestClient.addUser(user, group);

        // Test if the SaveResult is correct.
        Assert.assertEquals(result, saveResult);
    }
hs1rzwqc

hs1rzwqc1#

根据Mockito的文档,这个特性是围绕Java 9构建的。
这个模拟器是围绕Java代理运行时附件设计的;这需要一个兼容JVM,它是JDK(或Java 9VM)的一部分。
如果您的版本早于9,则可以:
但是,如果在Java 9之前的非JDK VM上运行,则可以在启动JVM时使用-javaagent参数手动添加Byte Buddy Java代理jar。

相关问题