mardi 26 janvier 2016

Mock Spring restClient exchange calls

I am trying to unit test some Spring RestClient calls but I can't figure out how to make it work so I would be glad for any suggestions.

I have a code communicating with API which exposes Hateoas:

// Access root resource
final URI uri = new URI(apiUri);
RequestEntity<Void> request = RequestEntity.get(uri).accept(HAL_JSON).build();

final Resource<Object> rootLinks = restTemplate.exchange(request, new ResourceType<Object>() {
}).getBody();

final Links links = new Links(rootLinks.getLinks());

// Follow stores link
final Link innerLink = links.getLink("entities").expand();
request = RequestEntity.get(URI.create(innerLink.getHref())).accept(HAL_JSON).build();
final Resources<MyEntity> entities = restTemplate.exchange(request, new ResourcesType<MyEntity>() {
}).getBody();

// do some additional stuff with the entities here

This is my attempt to unit test this method:

@Mock
private RestTemplate restTemplate;

@InjectMocks
private final TestedObject testedObject = new TestedObject();

@Before
public void setUp() {
    // prepare some payload for the unit tests
    ....
}

@Test
public void test() throws URISyntaxException {
    Links links = new Links(new ArrayList<Link>());
    Resource<Object> rootLinks = new Resource<Object>("entities", links);

    ResponseEntity<Object> response1 = new ResponseEntity<Object>(rootLinks, HttpStatus.OK);

    when(restTemplate.exchange(any(RequestEntity.class), any(ResourceType.class))).thenReturn(response1);

    Resources<MyEntityt> entities = new Resources<>(preparedEntities, links);
    ResponseEntity<Object> response2 = new ResponseEntity<Object>(entities, HttpStatus.OK);

    when(restTemplate.exchange(any(RequestEntity.class), any(ResourcesType.class))).thenReturn(response2);

    testedObject.execute();

    // verify the outcome
}

I am having two problems at the moment. First of all, I got an exception java.lang.ClassCastException: org.springframework.hateoas.Resources cannot be cast to org.springframework.hateoas.Resource. And second, I am testing two restTemplate exchange calls which differs only in the parameterized value (Object vs MyEntity) but I don;t know how to distinquish those in the test.

Aucun commentaire:

Enregistrer un commentaire