【问题标题】:How to mock the ResponseEntity<?> with generic type?如何使用泛型模拟 ResponseEntity<?>?
【发布时间】:2019-03-19 02:14:21
【问题描述】:

我需要模拟一个服务。我在模拟课程时在ResponseEntity&lt;?&gt; resp 中得到空值。

需要模拟的方法:

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的值并保存为列表。当我嘲笑 when(restC.SomeMethod(client)).thenReturn(resp); 方法时,它点击了 URL,但我作为响应得到的值 resp 为 null 。 所以在这里我将resp 的值设为null。我在邮递员中检查了 URL(someUrl) 它返回的值。

如何模拟ResponseEntity&lt;?&gt;

谢谢。

【问题讨论】:

标签: java web-services spring-boot junit mockito


【解决方案1】:

首先,创建一个ResponseEntity 对象:

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

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

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

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

注意点:

避免在@Service class 中使用ResponseEntity。您应该在@RestController class 中使用ResponseEntity

你可以使用@Autowired注解Inject你的@Service class,比如:

@RestController
public class YourControllerClass {

    @Autowired
    private YourServiceClass yourServiceClass;

或者使用constructor,比如:

@RestController
public class YourControllerClass {

    private YourServiceClass yourServiceClass;

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

所以:

@Service class 将处理 business or data objects@RestController class 将处理 ResponseRequest 对象。这样我们就有了Single Responsibility的原则。


一些不错的链接:

希望这会有所帮助!

【讨论】:

  • 我通过建议、示例和一些不错的链接改进了我的答案;)我希望这会对你有所帮助。
猜你喜欢
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
相关资源
最近更新 更多