测试spring hibernate dao和服务层

时间:2014-09-04 20:48:09

标签: java spring hibernate spring-mvc junit

对于我来说,为服务和dao层配置单元测试是一项挑战。我曾尝试过一些教程,但我仍然无法进行测试。

我的UserAccountService:

@Transactional(readOnly=true, rollbackFor={UserAccountNotFoundException.class})     
public UserAccount findById(int id) throws UserAccountNotFoundException {
    LOGGER.debug("Find an UserAccount entry with id: {}" + id);
    return userDao.findById(id);
}

我的Userdao

public UserAccount findById(int id) {
    return (UserAccount) session.get(UserAccount.class, id);
}

我的spring-servlet.xml:

<context:component-scan base-package="com.isad" />
<mvc:annotation-driven />

<mvc:resources mapping="/resources/**" location="/WEB-INF/" cache-period="31556926"/>

<!-- 
    Initialize base viewers 
--> 
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/jsp/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<!-- 
    Error Messages Handling
 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages" />
    <property name="defaultEncoding" value="UTF-8" />
</bean>


<!-- 
    Enable Data Transaction to Database. 
-->
<bean id="sessionFactory" scope="singleton"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id ="transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name = "sessionFactory" ref = "sessionFactory"/>
</bean>

我目前的测试配置:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-servlet.xml"})
@TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)
@Transactional
public class TestUserAccountDao {
@Autowired
UserAccountService userManager; 

@Test
@Transactional
public void testFindUser() throws UserAccountNotFoundException {    
    UserAccount other = userManager.findById(1);
    System.out.println("Hello User: " + other.getUsername());
}

我在运行上述测试时遇到的问题:

Testing begin
Hibernate: select this_.USER_ID as y0_, this_.USERNAME as y1_, this_.EMAIL as y2_, this_.DISPLAYNAME as y3_ from USER_ACCOUNT this_ where this_.USER_ID=? and this_.ENABLED=? and this_.role=?
UserAccount [id=0, username=null, email=null, password=null, firstname=null, lastname=null, displayname=null, fullName=null, phone=null, fax=null, role=CUSTOMER, enabled=true, createOn=Thu Sep 04 13:45:31 PDT 2014]
INFO | 2014-09-04 13:45:31,084 | TransactionalTestExecutionListener.java | 298 | Rolled back transaction after test execution for test context [DefaultTestContext@160abda0 testClass = TestUserAccountDao, testInstance = com.isad.test.dao.TestUserAccountDao@1b275eae, testMethod = testFindUser@TestUserAccountDao, testException = java.lang.NullPointerException, mergedContextConfiguration = [MergedContextConfiguration@35b8ff6f testClass = TestUserAccountDao, locations = '{classpath:spring-servlet.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
INFO | 2014-09-04 13:45:31,088 | AbstractApplicationContext.java | 873 | Closing org.springframework.context.support.GenericApplicationContext@625a80df: startup date [Thu Sep 04 13:45:28 PDT 2014]; root of context hierarchy

我的hibernate.cfg.xml和spring-servlet.xml位于src / main / resources下。

1 个答案:

答案 0 :(得分:1)

您的测试中有一个NPE,并且是一个RuntimeException,TransactionalTestExecutionListener已捕获它并回滚您当前正在执行的事务。

由于我没有看到任何DBUnit或任何其他代码来插入id = 1的用户,我只能假设您的数据库中没有用户,这就是为什么:

session.get(UserAccount.class, id);

返回null。

尝试更改此内容:

System.out.println("Hello User: " + other.getUsername());

if(other != null) {
    System.out.println("Hello User: " + other.getUsername());
} else {
    System.out.println("No User found for id : 1 ");
}