我正在尝试为以下代码编写单元测试:
public DesiredCapabilities findCapability(Platforms platform, Types type, String browser, double platformVersion) throws Exception{
Criteria criteria = getSession().createCriteria(BrowserCapabilities.class)
.add(Restrictions.eq("status", ICommonConstants.DB_STATUS_ACTIVE))
.add(Restrictions.eq("platformName", platform.getValue()))
.add(Restrictions.eq("browserName", browser))
.add(Restrictions.eq("platformVersion", platformVersion))
.addOrder(Order.desc("browserVersion"))
.setMaxResults(1);
Object res = criteria.uniqueResult();
if(res!=null)
return this.prepareBrowserCapability((BrowserCapabilities)res);
return null;
}
模拟代码是:
private BrowserCapabilityDAO mockBrowserCapability;
private Session mockSession;
private Criteria mockCriteria;
private Criterion mockCriterion;
@Before
public void init() {
mockBrowserCapability = Mockito.spy(new BrowserCapabilityDAO());
mockSession = Mockito.mock(Session.class, Mockito.RETURNS_DEEP_STUBS);
mockCriteria = Mockito.mock(Criteria.class, Mockito.RETURNS_DEEP_STUBS);
mockCriterion = Mockito.mock(Criterion.class, Mockito.RETURNS_DEEP_STUBS);
}
@Test
public void testFindCapability() throws Exception {
DesiredCapabilities desiredCapability = new DesiredCapabilities();
BrowserCapabilities mockBrowserCapabilities = getMockBrowserCapabilities();
//Stub
Mockito.doReturn(mockSession).when(mockBrowserCapability).getSession();
Mockito.when(mockSession.createCriteria(Mockito.eq(BrowserCapabilities.class))).thenReturn(mockCriteria);
Mockito.doReturn(mockCriteria).when(mockCriteria).add(mockCriterion);
Mockito.when(mockCriteria.addOrder(Mockito.any(Order.class))).thenReturn(mockCriteria);
Mockito.when(mockCriteria.setMaxResults(Mockito.anyInt())).thenReturn(mockCriteria);
Mockito.when(mockCriteria.uniqueResult()).thenReturn((Object)mockBrowserCapabilities);
//Mockito.doReturn(desiredCapability).when(mockBrowserCapability).prepareBrowserCapability(mockBrowserCapabilities);
mockBrowserCapability.findCapability(Platforms.WINDOWS, Types.COMPUTER, "FF", 10.0);
}
private BrowserCapabilities getMockBrowserCapabilities() {
BrowserCapabilities mockBrowserCapabilities = new BrowserCapabilities();
mockBrowserCapabilities.setBrowserName("browserName");
mockBrowserCapabilities.setBrowserVersion("browserVersion");
return mockBrowserCapabilities;
}
但是我在ClassCastException
处获得了
return this.prepareBrowserCapability((BrowserCapabilities)res);
无法转换为com.common.xxx.persistence.beans.BrowserCapabilities
。