gpt4 book ai didi

java - 如何使用泛型类型模拟 ResponseEntity

转载 作者:行者123 更新时间:2023-11-30 05:58:05 28 4
gpt4 key购买 nike

我需要模拟一项服务。我在ResponseEntity<?>中得到空值一边 mock 全类同学一边回答。

需要模拟的方法:

public List<Expression> getExpression(String expressView, Localdate date) {

List<Expression> =new ArrayList<>();
Map<String, Object> uri = new HashMap<>();
UriComponenetsBuilder build =
UriComponentsBuilder.fromHttpUrl("someUrl" + "/" + expressView);
build.queryParam(someParameter, someParameter);
build.queryParam(someParameter, someParameter);
build.queryParam(someParameter, someParameter);

HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON);
RestClient client = new RestClient(
build.build().encode.toUriString, HttpMethod.GET.Uri, header
);

ResponseEntity<?> resp = restC.SomeMethod(client);

if (resp = !null) {
//it goes to these line
}

}

在我的模拟方法中:

when(restC.SomeMethod(client)).thenReturn(resp);

所以上面的方法调用服务获取一些数据,获取expressView的值并保存为列表。当我 mock 该方法时 when(restC.SomeMethod(client)).thenReturn(resp);它击中了 URL,但我得到的响应值 resp一片空白 。所以我在这里得到resp值为null 。我检查了 postman 中的 URL(someUrl) 它返回的值。

如何模拟ResponseEntity<?>

谢谢。

最佳答案

首先,创建一个 ResponseEntity 对象:

HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_JSON);

ResponseEntity<?> responseEntity = new ResponseEntity<>(
"some response body",
header,
HttpStatus.OK
);

然后构建一个模拟以返回 responseEntity 对象:

when(restC.SomeMethod(client)).thenReturn(responseEntity);
<小时/>

注意点:

Avoid to use ResponseEntity inside @Service class. You should use ResponseEntity in @RestController class.

您可以使用@Autowired注释注入(inject)您的@Service类,例如:

@RestController
public class YourControllerClass {

@Autowired
private YourServiceClass yourServiceClass;

或者使用构造函数,例如:

@RestController
public class YourControllerClass {

private YourServiceClass yourServiceClass;

public YourControllerClass(YourServiceClass yourServiceClass) {
this.yourServiceClass= yourServiceClass;
}

所以:

@Service class will handle business or data objects and @RestController class will handle Response and Request objects. Thus we have Single Responsibility principle.

<小时/>

一些不错的链接:

希望这有帮助!

关于java - 如何使用泛型类型模拟 ResponseEntity<?> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52803383/

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