A simple way to test JPA entities in a Java SE environment

Source: Internet
Author: User
Tags java se

A simple way to test JPA entities in a Java SE environment

For software quality reasons, all the code we write is theoretically tested. JPA testing is not as convenient as a normal component, because JPA involves a database, so integration testing is essential, and a test framework like Arquillian can handle more complex integration tests, but its configuration is a bit more complex, so this article focuses on the Java The method of testing JPA entities (entity) in the SE environment more easily.

The goals we need to achieve are: 1. mysql is not required for additional installation of the database; 2. You can test directly in the SE environment.

Related tools We mainly use the Junit,maven. Refer to my GitHub repository for relevant source code.

Add dependency

pom.xmlAdd the following dependencies in:

<dependency>  <groupId>Junit</groupId>  <artifactId>Junit</artifactId>  <version>4.12</version>  <scope>Test</scope></dependency><dependency>  <groupId>Com.h2database</groupId>  <artifactId>H2</artifactId>  <version>1.4.196</version>  <scope>Test</scope></dependency><dependency>  <groupId>Org.hibernate.javax.persistence</groupId>  <artifactId>Hibernate-jpa-2.1-api</artifactId>  <version>1.0.2.Final</version></dependency><dependency>  <groupId>Org.hibernate</groupId>  <artifactId>Hibernate-core</artifactId>  <version>5.2.10.Final</version></dependency>

We used the H2 database, Jpa2.1-api and hibernate.

JPA Entities

Suppose we want to test the entity for this (omitting Getter/setter):

src/main/java/com/github/holyloop/entity/Book.java

@Entity@Table"book")publicclass Book {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    @Columntruefalse)    private Long id;    @Columnfalse)    private String title;    @Columnfalse)    private String author;}
Persistence Unit

To add a persistence unit declaration to a test resource:

src/test/resources/META-INF/persistence.xml

<?xmlVersion= "1.0" encoding= "UTF-8"?><persistenceversion="2.1"xmlns="Http://xmlns.jcp.org/xml/ns/persistence"xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation="http://xmlns.jcp.org/xml/ns/persistencehttp://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd ">  <persistence-unitname="Test"transaction-type="Resource_local">    <class>Com.github.holyloop.entity.Book</class>    <properties>      <!--Configuring JDBC properties --      <propertyname="Javax.persistence.jdbc.url"value="Jdbc:h2:mem:test;db_close_delay=-1;init=runscript from ' classpath:create.sql ';runscript from ' classpath:data.sql ' " />      <propertyname="Javax.persistence.jdbc.driver"value="Org.h2.Driver" />      <!--Hibernate Properties --      <propertyname="Hibernate.archive.autodetection"value="class, HBM" />      <propertyname="Hibernate.dialect"value="Org.hibernate.dialect.H2Dialect" />      <propertyname="Hibernate.format_sql"value="true" />      <propertyname="Hibernate.show_sql"value="true" />    </properties>  </persistence-unit></persistence>

The persistence unit is named, the test H2 database driver is added, and several hibernate-specific properties are declared, which will output some
Formatted debugging information to facilitate troubleshooting issues.

Test class SQL

Let's start by adding a few SQL files:

src/test/resources/create.sql:

-- bookdroptableifexists `book`;createtable book (  id bigint(20notnull auto_increment,  varchar(50notnull,  varchar(20notnull,  primarykey (id));

src/test/resources/data.sql:

DELETEFROM book;INSERTINTO book(idVALUES (1‘Spring in Action‘‘Craig Walls‘);

Of course you can also persistence.xml declare in:

<property name="hibernate.hbm2ddl.auto" value="create-drop"/>

Instead of create.sql files. The above attribute will automatically convert our entity declaration to the corresponding DDL, and the data will be deleted after the end
。 I use Create.sql on my side just for personal preference.

The test data can be inserted randomly in the data.sql.

Java

Let's take a look at our basic test class:

src/test/java/com/github/holyloop/entity/BaseTest.java:

protectedstatic EntityManagerFactory emf;protectedstatic EntityManager em;@BeforeClasspublicstaticvoidinit() {  emf = Persistence.createEntityManagerFactory("test");  em = emf.createEntityManager();}@AfterClasspublicstaticvoidtearDown() {  em.clear();  em.close();  emf.close();}

The Entity Manager Factory EMF and entity manager em are declared here, init tearDown respectively, and executed when the test class is initialized and destroyed, and the Init negative
Initialize the Entity Manager em,teardown to release the corresponding resource. We continue to add the following method to the basic test class:

@Before Public void Initdb() {Session session = EM.Unwrap(Session.)class); Session.doWork(New  Work() {@Override     Public void Execute(Connection Connection)throwsSQLException {Try{File script =NewFile (GetClass().GetResource("/data.sql").GetFile()); RunScript.Execute(Connection,NewFileReader (script)); }Catch(FileNotFoundException e) {Throw NewRuntimeException ("could not initialize with script"); }    }  });}@After Public void  Clean() {em.Clear();}

This way all of our subclass test methods pre-load data.sql the data in the beginning, and the entity manager clears the persistence context after the end so that the test methods do not affect each other.

Next we implement a simple test:

src/test/java/com/github/holyloop/entity/BookTest.java:

 Public classBooktestextendsbasetest {@Test     Public void Testaddbook() {Book book =NewBook (); Book.Settitle("new book"); Book.Setauthor("new Author"); Em.gettransaction().begin(); Em.persist(book); Em.gettransaction().Commit();@SuppressWarnings("Rawtypes") List books = em.CreateQuery("Select B from book B").getresultlist();assertequals(2, books.size()); }@Test     Public void Testquerybook() {Book book = em.Find(Book.class, 1L);Assertnotnull(book); }}

BookTestInheriting the basic test class we implemented above, here I implemented two basic tests to testAddBook see if I could successfully add a new book and testQueryBook test whether we could find the data.sql test data that we inserted in.

Test

After the test case is written, you can start testing and go to your project root directory some-path/your-project :

Perform:

mvn clean test

If everything works, the test results are as follows:

The above is the method of testing JPA entities without additional installation of the database, independent of other containers.

A simple way to test JPA entities in a Java SE environment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.