我需要模拟服务。我在模拟类时在ResponseEntity<?>响应中为null。

需要模拟的方法:

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<?>

谢谢。

最佳答案

首先,创建一个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);




注意点:


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


您可以使用Inject注释@Service class您的@Autowired,例如:

@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原理。




一些不错的链接:


Spring MVC - Using RequestEntity and ResponseEntity
How do I mock a REST template
Building REST services with Spring
Understanding the Single Responsibility Principle


希望这可以帮助!

10-08 18:55