我收到以下错误:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account
用下面的代码
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);
我有什么理由做不到吗get(0)
?
这个问题来自杰克逊。当它没有足够的信息来了解要反序列化到哪个类时,它会使用LinkedHashMap
.
由于您没有告知杰克逊您的元素类型ArrayList
,它不知道您想要反序列化为ArrayList
of Account
s。所以它会恢复到默认值。
相反,你可能可以使用as(JsonNode.class)
,然后处理ObjectMapper
以比安心所允许的更丰富的方式。像这样的东西:
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.convertValue(
accounts,
new TypeReference<List<Account>>(){}
);
assertThat(accountList.get(0).getId()).isEqualTo(expectedId);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)