如何用通用类型模拟ResponseEntity <!-?->?

时间:2018-10-14 13:56:29

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

我需要模拟服务。我在模拟类时在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<?>

谢谢。

1 个答案:

答案 0 :(得分:1)

First, create a ResponseEntity object:

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

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

Then build a mock:

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

Point to pay attention:

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

And you can Inject you @Service class using @Autowired annotation, like:

@RestController
public class YourClass {

    @Autowired
    private YourClassService yourClassService;

So:

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


Some nice links:

希望这会有所帮助!