Java Spring/Hibernate/Junit 针对 HSQLDB 测试 DAO 的示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2861796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:49:19  来源:igfitidea点击:

Spring/Hibernate/Junit example of testing DAO against HSQLDB

javahibernatespringjunithsqldb

提问by Ryan P.

I'm working on trying to implement a JUnittest to check the functionality of a DAO. (The DAO will create/read a basic object/table relationship).

我正在尝试实施JUnit测试来检查 DAO 的功能。(DAO 将创建/读取一个基本的对象/表关系)。

The trouble I'm having is the persistence of the DAO (for the non-test code) is being completed through an in-house solution using Spring/Hibernate, which eliminates the usual *.hbm.xmltemplates that most examples I have found contain.

我遇到的问题是 DAO(对于非测试代码)的持久性是通过使用Spring/Hibernate的内部解决方案完成的,这消除了*.hbm.xml我发现的大多数示例包含的常用模板。

Because of this, I'm having some trouble understanding how to setup a JUnittest to implement the DAO to create/read (just very basic functionality) to an in-memory HSQLDB. I have found a few examples, but the usage of the in-house persistence means I can't extend some of the classes the examples show (I can't seem to get the application-context.xml setup properly).

因此,我在理解如何设置JUnit测试以实现 DAO 以创建/读取(只是非常基本的功能)到内存中的HSQLDB 时遇到了一些麻烦。我找到了一些示例,但内部持久性的使用意味着我无法扩展示例显示的某些类(我似乎无法正确设置 application-context.xml)。

Can anyone suggest any projects/examples I could take a look at (or any documentation) to further my understanding of the best way to implement this test functionality? I feel like this should be really simple, but I keep running into problems implementing the examples I have found.

任何人都可以建议我可以查看(或任何文档)的任何项目/示例,以进一步了解实现此测试功能的最佳方法?我觉得这应该很简单,但我一直遇到实现我发现的示例的问题。

edit:

编辑:

Here's my solution for better readability, for anyone who needs a hand getting things going:

这是我的解决方案,以提高可读性,适合任何需要帮助的人:

  • My TestClass:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:applicationContextTest-Example.xml")
    @Transactional
    public class ExampleDaoTest extends AbstractTransactionalJUnit4SpringContextTests {
        @Resource(name = "sessionFactory")
        private SessionFactory exampleSessionFactory;
    
        @Resource(name = "exampleDao")
        private ExampleDao exampleDao;
    
  • My applicationContext.xmlfile:

    <!-- List of Daos to be tested -->
    <bean id="exampleDao" class="org.myExample.ExampleDao"/>
    
    <!-- Datasource -->
    <bean id="example_dataSource"
          class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:mem:ExampleTest"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>
    
    <!-- Session Factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="example_dataSource"/>
        <property name="annotatedClasses">
            <list>
                <value>org.myExample.ExampleClass</value>
            </list>
        </property>
        <property name="hibernateProperties">
            .... left to user to choose properties
        </property>
    </bean>
    
  • 我的TestClass

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:applicationContextTest-Example.xml")
    @Transactional
    public class ExampleDaoTest extends AbstractTransactionalJUnit4SpringContextTests {
        @Resource(name = "sessionFactory")
        private SessionFactory exampleSessionFactory;
    
        @Resource(name = "exampleDao")
        private ExampleDao exampleDao;
    
  • 我的applicationContext.xml文件:

    <!-- List of Daos to be tested -->
    <bean id="exampleDao" class="org.myExample.ExampleDao"/>
    
    <!-- Datasource -->
    <bean id="example_dataSource"
          class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:mem:ExampleTest"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>
    
    <!-- Session Factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="example_dataSource"/>
        <property name="annotatedClasses">
            <list>
                <value>org.myExample.ExampleClass</value>
            </list>
        </property>
        <property name="hibernateProperties">
            .... left to user to choose properties
        </property>
    </bean>
    

采纳答案by Bozho

Spring 3 offers a new jdbcnamespace that includes support for embedded databases, including HSQLDB. So that takes care of that part.

Spring 3 提供了一个新的jdbc命名空间,包括对嵌入式数据库的支持,包括 HSQLDB。所以这会处理那部分。

I'm wondering what the "in-house solution" could be. You can use annotations (either JPA or Hibernate annotations) to ORM your domain objects, so why do you need an "in-house solution"? E.g.:

我想知道“内部解决方案”可能是什么。您可以使用注释(JPA 或 Hibernate 注释)来 ORM 域对象,那么为什么需要“内部解决方案”呢?例如:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
    p:dataSource-ref="dataSource"
    p:packagesToScan="myapp.model" />

As far as implementing a test goes, use Spring's TestContext Framework. A test can look like this (again I'm assuming Spring 3 below, though it should work in Spring 2.5 simply by changing @Inject to @Autowired):

就实现测试而言,请使用 Spring 的 TestContext Framework。一个测试看起来像这样(我再次假设下面是 Spring 3,尽管它应该可以在 Spring 2.5 中工作,只需将 @Inject 更改为 @Autowired):

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
    "/beans-datasource-it.xml",
    "/beans-dao.xml",
    "/beans-service.xml",
    "/beans-web.xml" })
@Transactional
public class ContactControllerIT {
    @Inject private ContactController controller;

    ... setUp() and tearDown() ...

    @Test
    public void testGetContact() {
        String viewName = controller.getContact(request, 1L, model);

        ... assertions ...
    }
}

You'd put the embedded database inside beans-datasource-it.xml, for example. ('it' here stands for integration test, and the files are on the classpath.) The controller in this example lives in beans-web.xml, and will be autowired into the ContactControllerfield.

例如,您可以将嵌入式数据库放在 里面beans-datasource-it.xml。('it' 在这里代表集成测试,文件在类路径上。)这个例子中的控制器位于 中beans-web.xml,并且会自动连接到该ContactController字段中。

That's just an outline of what to do but hopefully it's enough to get you started.

这只是要做什么的大纲,但希望它足以让你开始。

回答by mdma

The bottom line with hibernate is the SessionFactory- your in-house solution will most likely be creating one of these somehow. Find out how, and then add a bean to create one in your test app context in the same way (or if possible using your in-house code that is used at runtime.). You may need to create your own FactoryBeanto do the instantiation. (Use AbstractFactoryBeanas your base class.)

休眠的底线是SessionFactory- 您的内部解决方案很可能会以某种方式创建其中之一。找出方法,然后添加一个 bean 以相同的方式在您的测试应用程序上下文中创建一个 bean(或者如果可能,使用您在运行时使用的内部代码。)。您可能需要创建自己的FactoryBean来进行实例化。(使用AbstractFactoryBean作为基类。)

Once this is in place, most of the examples using LocalSessionFactoryBean can be migrated to your situation - instead of using LocalsessionFactoryBean, use your custom factory bean.

一旦到位,大多数使用 LocalSessionFactoryBean 的示例都可以迁移到您的情况 - 而不是使用 LocalsessionFactoryBean,而是使用您的自定义工厂 bean。

(If you've not done so already, look at the Testingsection in the spring reference - it makes testing with Spring, and injecting tests with beans from the context a breeze.)

(如果您还没有这样做,请查看spring 参考中的测试部分 - 它使使用 Spring 进行测试,并使用上下文中的 bean 注入测试变得轻而易举。)

回答by Bozho

See here. It assumes maven2 as build tool, but you can easily use anything.

见这里。它假定 maven2 作为构建工具,但您可以轻松使用任何东西。

回答by rhinds

I have recently implemented a similar solution in some of my code using Hibernate, Springand HSQLDB.

我最近使用HibernateSpringHSQLDB在我的一些代码中实现了一个类似的解决方案

Its is worth noting that AbstractTransactionalJUnit4SpringContextTestshas now be deprecated - but it is still pretty straight forward to test - I cover most the details here: http://automateddeveloper.blogspot.com/2011/05/hibernate-spring-testing-dao-layer-with.html

值得注意的是,AbstractTransactionalJUnit4SpringContextTests现在已被弃用 - 但它仍然可以直接进行测试 - 我在这里介绍了大部分细节:http: //automateddeveloper.blogspot.com/2011/05/hibernate-spring-testing-dao-layer -with.html

回答by Joe

My application context looks a bit different

我的应用程序上下文看起来有点不同

<beans:bean class="org.apache.commons.dbcp.BasicDataSource" id="HSQL_DS">
    <beans:property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
    <beans:property name="url" value="jdbc:hsqldb:mem:Test"/>
    <beans:property name="username" value="sa"/>
    <beans:property name="password" value=""/>
</beans:bean>
<jdbc:embedded-database id="HSQL_DS">
    <jdbc:script location="classpath:schema.sql"/>
    <jdbc:script location="classpath:data.sql"/>
</jdbc:embedded-database>

and my test class looks like this:

我的测试课是这样的:

public class Tester {

    private EmbeddedDatabase db;

    @Before
     public void setUp(){
        db = new EmbeddedDatabaseBuilder().addDefaultScripts().build();


    }

    @Test
    public void TestMe(){
        System.out.println("Testing");
    }


    @After
    public void tearDown(){

        db.shutdown();
    }
}