gpt4 book ai didi

java - 如何模拟 sun jersey 客户邮寄电话?

转载 作者:行者123 更新时间:2023-11-29 04:11:57 25 4
gpt4 key购买 nike

这是我的代码

@Service
public class PaymentHandler {
private static final Gson GSON = new Gson();

private static Client webServiceClient = createSslClient(); // function creates a ssl connection

public Response makePayment(String payload) {
WebResource webResource = webServiceClient.resource(url);

WebResource.Builder builder = webResource.getRequestBuilder();

String r = builder
.type(MediaType.APPLICATION_JSON_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE)
.post(String.class, payload);

Response response = GSON.fromJson(r, Response.class);
}
}

这是我尝试测试它的方法,但它不起作用,它总是调用支付服务。我无法 mock 它。

Client client = mock(Client.class );
WebResource webResource = mock(WebResource.class);
WebResource.Builder builder = mock(WebResource.Builder.class);
ClientResponse clientResponse = mock(ClientResponse.class);
when(client.resource(anyString())).thenReturn(webResource);
when(webResource.getRequestBuilder()).thenReturn(builder);

when(builder.type(anyString())).thenReturn(builder);
when(builder.accept(anyString())).thenReturn(builder);
when(builder.post(Matchers.eq(String.class), anyString())).thenReturn("Test");
paymentHandler.makePayment(payload); //assume that I send actual payload

有人可以告诉我如何模拟这个吗?

最佳答案

下面是我如何模拟它

@Mock
Client client;

@Mock
WebResource webResource;

@Mock
WebResource.Builder builder;


@Test
public void test() {
ReflectionTestUtils.setField(payeezyHandler,"webServiceClient",client);
Mockito.when(client.resource(anyString())).thenReturn(webResource);
Mockito.when(webResource.getRequestBuilder()).thenReturn(builder);

Mockito.when(builder.type(MediaType.APPLICATION_JSON_TYPE)).thenReturn(builder);
Mockito.when(builder.accept(MediaType.APPLICATION_JSON_TYPE)).thenReturn(builder);
Mockito.when(builder.post(Matchers.eq(String.class),anyString())).thenReturn(fakeResponse());
}

我知道 ReflectionTestUtils 不好用。但是,如果您的测试类只有一个公共(public)函数要测试,那么我想没有什么坏处。

关于java - 如何模拟 sun jersey 客户邮寄电话?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54614231/

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