Java PowerMockito类强制转换异常

Java PowerMockito类强制转换异常,java,junit,powermockito,Java,Junit,Powermockito,我正在使用PowerMockito测试一个静态方法,但不幸的是得到了ClassCastException。请注意,如果我没有遵守语法规则,请务必确认 要测试的代码: List<IClientUserPrefDto> proxyPrefs = (List<IClientUserPrefDto>) DtoUtils.getClientPrefenceByEntityAndAttribute(config.geteSignatureSecurityUser().getUserP

我正在使用
PowerMockito
测试一个
静态方法
,但不幸的是得到了
ClassCastException
。请注意,如果我没有遵守语法规则,请务必确认

要测试的代码:

List<IClientUserPrefDto> proxyPrefs = (List<IClientUserPrefDto>) DtoUtils.getClientPrefenceByEntityAndAttribute(config.geteSignatureSecurityUser().getUserPreferences(), entity, attribute);

您可以在
DtoUtils
中创建名为
getclientprefencebyentity和attributeaslist的新方法

static List<IClientUserPrefDto> getClientPrefenceByEntityAndAttributeAsList(...) {
     return (List<IClientUserPrefDto>) DtoUtils.getClientPrefenceByEntityAndAttribute(...
...
}

这是一个解决问题的方法。但是在这种情况下,方法
时肯定需要接收一个返回列表的方法。

您可以在
DtoUtils
中创建一个名为
GetClientPrefenceByEntityandAttributesList
的新方法

static List<IClientUserPrefDto> getClientPrefenceByEntityAndAttributeAsList(...) {
     return (List<IClientUserPrefDto>) DtoUtils.getClientPrefenceByEntityAndAttribute(...
...
}


这是一个解决问题的方法。但是在这种情况下,方法
时肯定需要接收一个返回列表的方法。

它看起来像
getClientPreferenceByEntityandAttribute
只返回
IClientUserPrefDto
的一个实例,而不是它的
ArrayList
。我知道,但是有什么办法可以解决这个问题吗?这实际上是它返回IClientUserRefDTO实例的问题。测试中的方法也将其强制转换为列表强制转换为
列表有两种不同的方法。您可以先初始化
列表
,然后调用
proxyPrefs.add((iclientUserRefdto)DtoUtils.getCl…)
或者不能将
proxyPrefs
作为
列表
。列表已经初始化,我已经向其中添加了IClientUserPref的实例。我无法更改代码以满足我的测试用例。它看起来像
getClientPrefenceByEntityAndAttribute
只返回
IClientUserRefdTo
的一个实例,而不是它的
ArrayList
。我知道这一点,但有什么解决办法吗?这实际上是它返回IClientUserRefDTO实例的问题。测试中的方法也将其强制转换为列表强制转换为
列表有两种不同的方法。您可以先初始化
列表
,然后调用
proxyPrefs.add((iclientUserRefdto)DtoUtils.getCl…)
或者不能将
proxyPrefs
作为
列表
。列表已经初始化,我已经向其中添加了IClientUserPref的实例。我无法更改代码以满足我的测试用例。我很确定这不会起作用。我在这里看到的问题是对列表的强制转换,您实际上只是将其移动到一个单独的函数,而没有解决问题。我认为异常发生在PowerMockito的
然后返回
方法中。此代码中没有强制转换异常
List proxyPrefs=(List)DtoUtils.getClientPrefenceByEntityAndAttribute(…)然后返回
方法中。此代码中没有强制转换异常
List proxyPrefs=(List)DtoUtils.getClientPrefenceByEntityAndAttribute(…)static List<IClientUserPrefDto> getClientPrefenceByEntityAndAttributeAsList(...) {
     return (List<IClientUserPrefDto>) DtoUtils.getClientPrefenceByEntityAndAttribute(...
...
}
PowerMockito.when(DtoUtils.getClientPrefenceByEntityAndAttributeAsList(anyListOf(IClientUserPrefDto.class),any(String.class),any(String.class))).thenReturn(list);