2013-09-24 67 views
0

我有這樣的測試:數據不添加到數據庫中測試

@ContextConfiguration(locations = {"classpath:/test/BeanConfig.xml"}) 
public class CandidateServiceTest extends AbstractTransactionalJUnit4SpringContextTests{ 

    @Autowired 
    CandidateService candidateService; 

    @BeforeClass 
    public static void initialize() throws Exception{ 

     UtilMethods.createTestDb(); 

    } 
    @Before 
    public void setup() { 
     TestingAuthenticationToken testToken = new TestingAuthenticationToken("testUser", ""); 
     SecurityContextHolder.getContext().setAuthentication(testToken); 
    } 

    @After 
    public void cleanUp() { 
     SecurityContextHolder.clearContext(); 
    } 
    @Test 
    public void add(){ 
     Candidate candidate = new Candidate(); 
     candidate.setName("testUser"); 
     candidate.setPhone("88888"); 
     candidateService.add(candidate);//here I should add data to database 
     List<Candidate> candidates = candidateService.findByName(candidate.getName()); 
     Assert.assertNotNull(candidates); 
     Assert.assertEquals("88888", candidates.get(0).getPhone()); 
    }     
} 

附加功能:在DAO

@Transactional 
@Service("candidateService") 
public class CandidateService { 
    public void add(Candidate candidate) { 
      Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
      String login = auth.getName(); 
      User user = utilService.getOrSaveUser(login); 
      candidate.setAuthor(user); 
      candidateDao.add(candidate); 
     } 
    ... 
} 

附加功能:

public Integer add(Candidate candidate) throws HibernateException{ 
     Session session = sessionFactory.getCurrentSession(); 
     if (candidate == null) { 
      return null; 
     } 
     Integer id = (Integer) session.save(candidate); 
     return id; 

    } 

通常candidateService.add(candidate)增加數據庫正常,但在測試中它不會添加到數據庫。我在測試後檢查數據庫以查看它。

可能是什麼問題?

UPDATE

配置:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" 
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd 
     http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 

<!-- Настраивает управление транзакциями с помощью аннотации @Transactional --> 
    <tx:annotation-driven transaction-manager="transactionManager" /> 

    <!-- Менеджер транзакций --> 
    <bean id="transactionManager" 
     class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name="sessionFactory" ref="sessionFactory" /> 
    </bean> 

    <!-- Непосредственно бин dataSource --> 
    <bean id="dataSource" 
     class="org.springframework.jdbc.datasource.DriverManagerDataSource" 
     p:driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" 
     p:url="jdbc:sqlserver://10.16.9.52:1433;databaseName=hhsystemTest;" 
     p:username="userNew" 
     p:password="Pass12345" /> 

    <!-- Настройки фабрики сессий Хибернейта --> 
    <bean id="sessionFactory" 
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
     <property name="dataSource" ref="dataSource" /> 
     <property name="configLocation"> 
      <value>classpath:test/hibernate.cfg.xml</value> 
     </property> 

     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.show_sql">true</prop> 
       <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> 
       <prop key="hibernate.connection.charSet">UTF-8</prop> 
<!--    <prop key="hibernate.hbm2ddl.auto">create-drop</prop> --> 
     </props> 
     </property> 
    </bean> 

</beans> 
+0

UtilMethods.createTestDb()是做什麼的? –

+0

1.刪除舊數據庫2.創建新數據庫3.從休眠狀態獲取ddl腳本並執行 – gstackoverflow

回答

0

嘗試增加周圍的方法@Transactional註釋在您的測試類。

此批註創建可與數據庫交互的會話。

0

candidateService.add之後發出沖洗。在測試方法周圍有一個事務,一個提交(和flush)只發生在方法執行之後。您必須通過刷新會話來「僞造」提交。只需在您的測試類中注入SessionFactory,並在當前會話中調用flush。

@ContextConfiguration(locations = {"classpath:/test/BeanConfig.xml"}) 
public class CandidateServiceTest extends AbstractTransactionalJUnit4SpringContextTests{ 

    @Autowired 
    private SessionFactory sessionFactory; 

    @Test 
    public void add(){ 
     Candidate candidate = new Candidate(); 
     candidate.setName("testUser"); 
     candidate.setPhone("88888"); 
     candidateService.add(candidate);//here I should add data to database 
     sessionFactory.getCurrentSession().flush(); //execute queries to database 
     List<Candidate> candidates = candidateService.findByName(candidate.getName()); 
     Assert.assertNotNull(candidates); 
     Assert.assertEquals("88888", candidates.get(0).getPhone()); 
    }     
} 

而且ofcourse確保您findByName方法也正確實現,並使用同一個Hibernate Session!

+0

「當然,確保您的findByName方法也可以正確實現並使用相同的休眠會話」 - 我該怎麼做? – gstackoverflow

+0

「圍繞測試方法進行交易」 - 爲什麼? – gstackoverflow

+0

我強烈建議您閱讀Sprnig參考指南(我在您的其他主題中指出您的測試章節)。 –

0

您必須使用@Autowired自動連線DAO中的sessionDactory實例並且我會將@Transactional註釋放在DAO的每個方法中,而不是在他定義服務類之前。這通常是在註解驅動的Spring應用程序中完成的方式。