使用JUnit测试JPA环境

时间:2022-05-06 20:36:15

1新建entity bean

1.1新建com.itcast.bean.product

1.2新建ProductType.java

@Entity标注是一个实体bean

(对象标识,字符串类型用UUID生成出来,可以用数值类型)

(@Id @Generated(strategy=GenerationType.AUTO)

package com.itcast.bean.product;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

 

//@Entity标注是一个实体bean

@Entity

public class ProductType {

 

    //对象标识,字符串类型用UUID生成出来,可以用数值类型

    private Integer typeid;

 

    @Id @GeneratedValue(strategy=GenerationType.AUTO)

    public Integer getTypeid() {

       return typeid;

    }

 

    public void setTypeid(Integer typeid) {

       this.typeid = typeid;

    }

}

 

2新建单元测试:

2.1New JUnit Test Case

(选择New JUnit 4 Testpackage:junit.testname:ProductTestclass under test导入JUnit4.jar)

2.2添加单元测试点

   (@Test) public void runtest()启动JPA框架

(Persistence.createEntityManagerFactory(“实体bean集合名”);

JPA规范,作为启动JPA框架的入口点)

package junit.test;

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

import org.junit.BeforeClass;

import org.junit.Test;

import com.itcast.bean.product.ProductType;

 

public class ProductTest {

    @BeforeClass

    public static void setUpBeforeClass() throws Exception {

    }

 

    /*

     * 添加单元测试点

     * (@Test) public void runtest()启动JPA框架

     */

    @Test

    public void runtest(){

       //(Persistence.createEntityManagerFactory(“实体bean集合名”); JPA规范,作为启动JPA框架的入口点)

       EntityManagerFactory factory = Persistence.createEntityManagerFactory("itcast");

       EntityManager em =factory.createEntityManager();

       em.getTransaction().begin();

       em.persist(new ProductType());

       em.getTransaction().commit();

       em.close();

       factory.close();

    }

}