数据不会在测试中添加到数据库

时间:2013-09-24 08:05:40

标签: java spring hibernate testing junit

我有这个测试:

@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());
    }                   
}

添加功能:

@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);
        }
    ...
}

在dao中添加功能:

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)正常地添加到数据库,但在测试中它不会添加到数据库。我在测试后检查了数据库,看看它。

可能是什么问题?

更新

配置:

<?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>

3 个答案:

答案 0 :(得分:0)

尝试在测试类中的方法周围添加@Transactional注释。

此注释创建一个可与数据库交互的会话。

答案 1 :(得分:0)

candidateService.add之后发出同花。测试方法周围有一个事务,只在方法执行后才发生提交(和刷新)。你必须通过刷新会话来“伪造”提交。只需在测试类中注入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());
    }                   
}

当然,确保您的findByName方法也正确实现并使用相同的休眠会话!

答案 2 :(得分:0)

您必须使用@Autowired在DAO中自动连接sessionDactory实例。我会将@ Transactional注释放在DAO的每个方法中,而不是在他定义服务类之前。这通常是在注释驱动的Spring应用程序中完成的方式。