How to test HQL queries?

后端 未结 7 504
深忆病人
深忆病人 2020-12-13 09:05

I\'m searching for a fast (really fast) way to test changes to hibernate queries. I have a huge application with thousands of different HQL queries (in XML files) and 100+ m

7条回答
  •  误落风尘
    2020-12-13 09:34

    You said the quickest way, I'm not sure if you meant the quickest way to get going, or the quickest way to perform ongoing tests, with some initial investment to get the tests implemented. This answer is more the latter.

    The way I've done this before was to implement some simple integration testing with JUnit and DBUnit.

    In essence, you'll be using DBUnit to set up your test database with a known and representative set of data, and then plain JUnit to exercise the methods containing your HQL queries, and verify the results.

    For instance,

    Set up your database first to contain only a fixed set of data e.g.,

    Product Name, Price
    Acme 100 Series Dynamite, $100
    Acme 200 Series Dynamite, $120
    Acme Rocket, $500
    

    This is something you'd do in your JUnit test case's setup() method.

    Now let's assume you have a DAO for this entity, and there's a "findProductWithPriceGreaterThan(int)" method. In your test, you'd do something like:

    public void testFindProductWithPriceGreaterThanInt() {
        ProductDAO dao = new HibernateProductDAO();
        //... initialize Hibernate, or perhaps do this in setup()
    
        List products = dao.findProductWithPriceGreaterThan(110);
        assertEquals(2, products.size());
        //... additional assertions to verify the content of the list.
    }
    

提交回复
热议问题