【问题标题】:Unit Test for DAO class: Java Spring MVC using Hibernate and H2 databaseDAO 类的单元测试:使用 Hibernate 和 H2 数据库的 Java Spring MVC
【发布时间】:2016-12-08 20:24:22
【问题描述】:

我正在尝试为我的 DAO 类编写 jUnit 测试,但在 eclipse 中运行以下测试时出现错误:

package com.bookstore.dao;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;    
import com.bookstore.domain.Book;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:**/applicationContext-test.xml"})
public class BookDaoImplTest {

    private BookDao bookDao;
    private Book book;

    @Before
    public void setup() {
        book = new Book();
        book.setBookName("Some Book Name");
        book.setBookCategory("Fiction");
        book.setBookPrice(11.11);
        // more properties here (not relevant for the question)
    }

    @Test
    @Rollback(true)
    public void testBookInsert() {
        bookDao.bookInsert(book);  // nullPointer happens at this line!
        final int bookId = book.getBookId();
        Book insertedBook = bookDao.getBookById(bookId);    
        Assert.assertEquals(insertedBook.getBookName(), book.getBookName());
    }
}

另外我的DAO实现类如下:

package com.bookstore.dao;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import com.bookstore.domain.Book;
import com.bookstore.exception.BookNotFoundException;

@Repository
@Transactional
public class BookDaoImpl implements BookDao {

    @Autowired
    private SessionFactory sessionFactory;
    private Session session = null;

    public List<Book> getAllBooks() {
        session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("FROM Book");
        List<Book> books = query.list();
        session.flush();
        return books;
    }

    public Book getBookById(int bookId) {
        session = sessionFactory.getCurrentSession();
        Book bookById = (Book) session.get(Book.class, bookId);
        session.flush();
        if (bookById == null) {
            throw new BookNotFoundException(bookId);
        }
        return bookById;
    }

    public void bookInsert(Book book) {
        session = sessionFactory.getCurrentSession();
        session.saveOrUpdate(book);
        session.flush();
    }

    // more methods here (not relevant for the question)
}

我还在src/test/resources文件夹下创建了applicationContext-test.xml,如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.h2.Driver" />
        <property name="url" value="jdbc:h2:tcp://localhost/~/test" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.Dialect">
                    org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan">
            <list><value>com.bookstore</value></list>
        </property>
    </bean>
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

现在我在 JUnit 窗口中遇到的错误是 NullPointerException 在我的测试的 bookDao.bookInsert(book); 行:

JUnit window of Eclipse

在控制台中我可以看到以下内容:

INFO: HHH000232: Schema update complete
Dec 08, 2016 10:16:41 PM org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
INFO: Using DataSource [org.springframework.jdbc.datasource.DriverManagerDataSource@23529fee] of Hibernate SessionFactory for HibernateTransactionManager
Dec 08, 2016 10:16:41 PM org.springframework.context.support.GenericApplicationContext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext@5dfcfece: startup date [Thu Dec 08 22:16:38 GMT 2016]; root of context hierarchy

【问题讨论】:

  • 将会话作为实例变量是错误的,线程可以同时访问会话或覆盖对它的引用。
  • 尝试为bookDao添加@Autowired
  • 内森,你的意思是我应该在每个方法中都有Session session = sessionFactory.getCurrentSession();,而不是实例变量private Session session = null;

标签: java spring hibernate junit


【解决方案1】:

可能您的 applicationContext.xml 文件不在单元测试的类路径中。尝试将其复制到测试包的资源文件夹中。

或者你已经在@Before setup方法中自己创建了dao,为什么还要使用@Autowired?

【讨论】:

  • 我在 src/test/resources 文件夹下创建了另一个文件 - applicationContext-test.xml 并删除了@Autowired 注释。看起来测试正在尝试运行,但仍然出现错误。当我调试时 - 在我的 BookDaoImpl 类的 session = sessionFactory.getCurrentSession(); 行抛出空指针。
  • 你是如何配置你的会话工厂的?如果它在一个 xml 文件中,它也可能从类路径中丢失
  • 会话工厂配置在文件夹src/test/resources下的applicatioContext-test.xml文件中
【解决方案2】:

我认为问题在于您在 BookDaoImplTest 中创建 BookDao 实例的方式。正确创建 BookDao 和其中引用的 bean 的唯一方法是通过依赖注入(例如使用 @Autowired)。如果您通过使用“new”运算符或通过模拟它手动创建它,则“sessionFactory”之类的字段可能为空(如果您不手动设置它们)。

【讨论】:

  • 如果我将@Autowired 添加到BookDao bookDao; 我会得到错误:SEVERE: Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@64616ca2] to prepare test instance [com.bookstore.dao.BookDaoImplTest@27494e46] org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.bookstore.dao.BookDaoImplTest': Unsatisfied dependency expressed through field 'bookDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found ...
  • 所以这意味着 spring 找不到你的 applicationContext-test.xml。在您的 BookDaoImplTest 中,您可以尝试将 @ContextConfiguration(locations = { "classpath:**/applicationContext-test.xml"}) 替换为 @ContextConfiguration(locations = { "classpath:applicationContext-test.xml"})
猜你喜欢
  • 1970-01-01
  • 2019-11-15
  • 2015-07-09
  • 2014-12-24
  • 1970-01-01
  • 2019-04-01
  • 2012-12-22
  • 2016-06-19
  • 2011-07-21
相关资源
最近更新 更多