Spring/Hibernate/Junit example of testing DAO against HSQLDB

后端 未结 5 1497

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

The trouble

5条回答
  •  灰色年华
    2021-02-02 14:15

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

    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.:

    
    

    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):

    @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 ContactController field.

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

提交回复
热议问题