模拟抽象类及其子类

时间:2016-10-19 07:48:19

标签: java unit-testing junit mockito

我需要模拟依赖库的类。

正确模拟了实际的实现类

@Mock
LocalContainerEntityManagerFactoryBean entityManagerFactoryBeanMock;

但是调用了它的抽象类,我不能模仿那个方法。

我目前正在使用Mockito。

我试图以这种方式嘲笑

@Mock(answer = Answers.RETURNS_DEEP_STUBS)

它以某种方式传递了电话, 但后来验证失败了。

这是完整的课程

@RunWith(MockitoJUnitRunner.class)
public class DatabaseConfigTest {

DatabaseConfig databaseConfig;

@Mock
DriverManagerDataSource dataSourceMock;

@Mock
JpaTransactionManager transactionManagerMock;

@Mock
EntityManagerFactory entityManagerFactoryMock;

@Mock
HibernateJpaVendorAdapter vendorAdapterMock;

@Mock(answer = Answers.RETURNS_DEEP_STUBS)
LocalContainerEntityManagerFactoryBean entityManagerFactoryBeanMock;

@Test
public void testEntityManagerFactory() throws Exception {
    doReturn(vendorAdapterMock).when(databaseConfig).getHibernateJpaVendorAdapter();
    doReturn(entityManagerFactoryBeanMock).when(databaseConfig).getLocalContainerEntityManagerFactoryBean();
    doReturn(dataSourceMock).when(databaseConfig).dataSource();

    EntityManagerFactory managerFactory = databaseConfig.entityManagerFactory();

    assertNotNull(managerFactory);
    verify(vendorAdapterMock, times(1)).setGenerateDdl(Boolean.TRUE);
    verify(entityManagerFactoryBeanMock, times(1)).setJpaVendorAdapter(vendorAdapterMock);
    verify(entityManagerFactoryBeanMock, times(1)).setDataSource(dataSourceMock);
    verify(entityManagerFactoryBeanMock, times(1)).afterPropertiesSet(); // method from abstract - this method i cannot mock
}
}

以下是实施代码:

factory.setJpaVendorAdapter(vendorAdapter); // mocked, it doesn't enter
factory.setDataSource(dataSource()); // mocked, it doesn't enter          
factory.afterPropertiesSet(); // method from abstract, it enters here but shouldn't

0 个答案:

没有答案