2014-09-04 242 views
1

對於我來說,配置服務和dao層的單元測試是一個很大的挑戰。我試圖遵循一些教程,但我仍然無法使測試工作。測試春天hibernate 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); 
} 

我的彈簧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 [[email protected] testClass = TestUserAccountDao, testInstance = [email protected], testMethod = [email protected], testException = java.lang.NullPointerException, mergedContextConfiguration = [[email protected] 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 [email protected]5a80df: startup date [Thu Sep 04 13:45:28 PDT 2014]; root of context hierarchy 

我的hibernate.cfg.xml和彈簧servlet.xml中位於在src /主/資源。

回答

1

你在你的測試中得到了一個N​​PE,並且是一個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 "); 
} 
+0

謝謝你的建議。你是完全正確的。該ID從不同的號碼開始 – 2014-09-04 22:04:35