0

How can I make a JUnit Test that tests NamedQueries?

I want a fail on syntaxis error like:

@Entity
@NamedQueries({
    @NamedQuery(name="Country.findByName",
            query="SELECT c FROM Country c WHERE c.wrongname = :name")
}) 
public class Country {
    private String name;
//...
}

The test should be fail because name < > wrongname

I only need syntaxis check, not DB check

StackTrace on runtime:

Caused by: javax.persistence.PersistenceException: [PersistenceUnit: unit] Unable to build EntityManagerFactory
...
Caused by: org.hibernate.HibernateException: Errors in named queries: Country.findByName
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:397)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1327)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
Omar Hrynkiewicz
  • 502
  • 1
  • 8
  • 21

1 Answers1

0

Although you talk about checking only the syntax, your example is about checking the query is consistent with the table columns. The most practical way to testing this isusing a database. Unit testing using a real client-server database is fraught with problems. But you can instead use an in memory embedded database such as Apache Derby for your unit tests. Recent versions of Spring have some helper code to make this even easier. The database unit tests will still be much slower than other unit tests, so you will need to keep them few in number to prevent your unit tests being slow.

Raedwald
  • 46,613
  • 43
  • 151
  • 237