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

添加功能:

@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>
4

3 回答 3

0

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

于 2013-09-24T08:16:19.527 回答
0

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

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

于 2013-09-24T08:08:04.647 回答
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方法也正确实施并使用相同的休眠会话!

于 2013-09-24T08:14:08.387 回答