如何测试dao层而不标记事务性类

时间:2017-10-28 18:10:03

标签: java spring unit-testing jpa testing

我应该为DAO层编写单元测试。我有这样的DAO课程:

@Repository
public class CustomerDaoImpl implements CustomerDao {

    @PersistenceContext
    private EntityManager em;

    // some methods ...
}

ApplicationContext.java中的应用程序上下文配置如下:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories
@ComponentScan(basePackages = "/*censored*/")
public class ApplicationContext {

    @Bean
    public JpaTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory().getObject());
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean jpaFactoryBean = new LocalContainerEntityManagerFactoryBean();
        jpaFactoryBean.setDataSource(db());
        jpaFactoryBean.setLoadTimeWeaver(instrumentationLoadTimeWeaver());
        jpaFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
        return jpaFactoryBean;
    }

    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean() {
        return new LocalValidatorFactoryBean();
    }

    @Bean
    public LoadTimeWeaver instrumentationLoadTimeWeaver() {
        return new InstrumentationLoadTimeWeaver();
    }

    @Bean
    public DataSource db() {
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.DERBY).build();
        return db;
    }
}

测试类就像这样:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationContext.class)
public class TestCustomerDao extends AbstractTestNGSpringContextTests 
{

    @Autowired
    private CustomerDao customerDao;

    @Test
    public void someTest() {
        // ... some test
    }
}

如何在不使用@Transactional注释标记DAO类的情况下运行单元测试?

我在其他SO帖子中读到@Transactional应该在服务层级别使用。但是,我应该为DAO层编写测试,没有任何服务层。

如果我没有使用@Transactional注释标记DAO类,我会收到以下错误:javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call来自正在调用的DAO类中的方法{ {1}}。

很抱歉,如果这是一个愚蠢的问题,但我对此都不熟悉。

1 个答案:

答案 0 :(得分:0)

看起来TestCustomerDao类缺少以下注释:@TestExecutionListeners(TransactionalTestExecutionListener.class)。现在一切正常。