首页 > 解决方案 > 如何对改造 Web API 调用进行单元测试

问题描述

我正在尝试测试使用 Retrofit 进行 @GET 调用的服务类。

我更新了我的测试用例,现在我正在使用 square 的 mock-retrofit 在他们的测试样本和其他一些示例之后模拟服务器。但我正在努力对调用改造接口的方法进行单元测试。

retrofit-mock 示例测试接口类。如何模拟实现接口方法的方法的改造调用。

public class XmattersApi {

    private XmattersInterface service;

    public GroupsResponse getGroupsWithSupervisor() throws IOException {
         String host = xmattersApiConfiguration.getHost();

         Interceptor interceptor = new Interceptor() {
             @Override
             public okhttp3.Response intercept(Chain chain) throws IOException {
                 Request newRequest = chain.request().newBuilder().addHeader("Authorization", "TestToken").build();
                 return chain.proceed(newRequest);
             }
         };

         OkHttpClient.Builder builder = new OkHttpClient.Builder();
         builder.interceptors().add(interceptor);
         OkHttpClient client = builder.build();

         Retrofit retrofit = new Retrofit.Builder()
                 .baseurl(getBaseUri(host).toUriString())
                 .addConverterFactory(JacksonConverterFactory.create())
                 .client(client)
                 .build();

         service = retrofit.create(XmattersInterface.class);

         Call<GroupsResponse> retrofitCall = service.getGroupsWithSupervisor("supervisors");

         Response<GroupsResponse> response = retrofitCall.execute();

         if (!response.isSuccessful()) {
             throw new IOException(response.errorBody() != null
                 ? response.errorBody().string(): "unknown error");
         }

         return response.body();

    }
}


我的接口类定义如下:

public interface XmattersInterface {

    @Headers({"Content-type: application/json;charset=UTF-8"})
    @GET("groups")
    Call<GroupsResponse> getGroupsWithSupervisor(@Query("embed") String embed);

}

我尝试模拟改造调用并在调用服务接口时返回模拟响应。

它不是在调用模拟。这是我更新的测试用例。

public class XmattersApiTest {

   XmattersApi xmattersAPi;

   XmattersInterfaceMock xmattersInterfaceMock;
  
   private final NetworkBehavior behavior = NetworkBehavior.create();


    @BeforeEach
    public void setUp() throws Exception {
        Retrofit retrofit = new Retrofit.Builder()
                .addCallAdapterFactory(JacksonConverterFactory.create())
                .baseUrl("http://example.com").build();
        MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit).networkBehavior(behavior).build();

       final BehaviorDelegate<XmattersInterface> delegate = mockRetrofit.create(XmattersInterface.class);

       xmattersInterfaceMock = new XmattersInterfaceMock(delegate);

    }

    @Test
    void testGroupsWithSupervisorCase_1() throws IOException {

       Call<GroupsResponse> call = mock(Call.class);
       XmattersInterface xmattersInterface =  mock(XmattersInterface.class)

       Call<GroupsResponse> mockCall = xmattersInterfaceMock.getGroupsWithSupervisor("supervisors");
       Response<GroupsResponse> mockResponse = mockCall.execute; // Mock data is received here from the XmattersInterfaceMock
       when(xmattersInterface.getGroupsWithSupervisor(ArgumentMatchers.anyString())).thenReturn(mockCall); 

       when(call.execute()).thenReturn(mockResponse)
       xmattersApi.getGroupsWithSupervisor(); //Fails with java.net.SocketTimeoutException error


    }

}

委托请求的服务模拟类:

public class XmattersInterfaceMock implements XmattersInterface {
    private final BehaviorDelegate<XmattersInterface> delegate;

    public XmattersInterfaceMock(BehaviorDelegate<XmattersInterface> delegate) {
        this.delegate = delegate;
    }

    @Override
    public Call<GroupsResponse> getGroupsWithSupervisor(String embed) {
        return delegate.returningResponse(getMockGroupsResponse()).getGroupsWithSupervisor(embed);
    }
}

我在这里做错了什么?有人请帮忙!

我正在使用 Springboot-JUnit,mockito

标签: javaspring-bootunit-testingmockitoretrofit

解决方案


推荐阅读