Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm getting below error:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

with below code

final int expectedId = 1;

Test newTest = create();

int expectedResponseCode = Response.SC_OK;

ArrayList<Account> account = given().when().expect().statusCode(expectedResponseCode)
    .get("accounts/" + newTest.id() + "/users")
    .as(ArrayList.class);
assertThat(account.get(0).getId()).isEqualTo(expectedId);

Is there a reason why I cannot do get(0)?

share|improve this question
    
Cannot be cast to what? What is the rest of the error message? –  Oliver Charlesworth Mar 3 at 0:02
    
@OliverCharlesworth also added entire stacktrace –  Passionate Developer Mar 3 at 0:05
1  
What's an Account? Why are you trying to cast to it from a map? –  Dave Newton Mar 3 at 0:06
    
For those of us who might be unfamiliar with the library, can you say what class this given() method is statically imported from? –  Mark Peters Mar 3 at 0:07
    
@DaveNewton Account is a model from Dropwizard which uses com.fasterxml.jackson.databind.annotations –  Passionate Developer Mar 3 at 0:08

1 Answer 1

up vote 1 down vote accepted

The issue's coming from Jackson. When it doesn't have enough information on what class to deserialize to, it uses LinkedHashMap.

Since you're not informing Jackson of the element type of your ArrayList, it doesn't know that you want to deserialize into an ArrayList of Accounts. So it falls back to the default.

Instead, you could probably use as(JsonNode.class), and then deal with the ObjectMapper in a richer manner than rest-assured allows. Something like this:

ObjectMapper mapper = new ObjectMapper();

JsonNode accounts = given().when().expect().statusCode(expectedResponseCode)
    .get("accounts/" + newClub.getOwner().getCustId() + "/clubs")
    .as(JsonNode.class);


//Jackson's use of generics here are completely unsafe, but that's another issue
List<Account> accountList = mapper.readValue(
    mapper.treeAsTokens(accounts), 
    new TypeReference<List<Account>>(){}
);

assertThat(accountList.get(0).getId()).isEqualTo(expectedId);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.