模拟持久性类返回iLlegalargumentException



当我尝试使用Event模拟类CC_1时,我已经有:

java.lang.IllegalArgumentException: Object: Mock for Event, hashCode: 640142691 is not a known entity type.

这是事件类:

@Entity
@Table(name = "event")
@XmlRootElement
public class Event implements Serializable {
    private static final long serialVersionUID = 1L;
   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Basic(optional = false)
   @Column(unique = true, name = "id")
   private Integer eventId;
   @Basic(optional = false)
   @NotNull
   @Size(min=1, max=255)
   @Column(name = "title")
   private String eventTitle;
   @Basic(optional = false)
   @JoinColumn(name = "created_by", referencedColumnName = "id")
   @ManyToOne
   private User eventCreatedBy;
   @Basic(optional = false)
   @Column(name = "created")
   @Temporal(TemporalType.TIMESTAMP)
   private Date eventCreated;
   public Event() {
   }
   // getters and setters for all database fields
   @Override
   public int hashCode() {
       int hash = 0;
       hash += (eventId != null ? eventId.hashCode() : 0);
       return hash;
   }
   @Override
   public boolean equals(Object object) { 
       if (!(object instanceof Event)) {
           return false;
       }
       Event other = (Event) object;
       if ((this.eventId == null && other.eventId != null) || (this.eventId != null && !this.eventId.equals(other.eventId))) {
           return false;
       }
       return true;
   }
   @Override
   public String toString() {
       return "Event[ eventId=" + eventId + " ]";
   }

这是测试类:

public class EventTest {
   private static final Integer EVENT_ID = 1;
   private static final String EVENT_TITLE = "title";
   private EntityManager em;
   private EntityTransaction et;
   private EventServiceImpl eventService;
   @Before
   public void setUp() throws Exception {
       em = Persistence.createEntityManagerFactory("test").createEntityManager();
       et = em.getTransaction();
       eventService = new EventServiceImpl();
       eventService.em = em;
       Event event = mock(Event.class);
       et.begin();
       em.persist(event);
   }
   @After
   public void tearDown() throws Exception {
       em.close();
   }
   @Test
   public void getList() {
       List list = eventService.getList();
       Event data = (Event) list.get(0);
       assertEquals(1, list.size());
       assertEquals(EVENT_TITLE, data.getEventTitle());
   }
   @Test
   public void getById() {
       Event data = eventService.get(EVENT_ID);
       assertEquals(EVENT_ID, data.getEventId());
   }
}

有人知道如何处理?

您试图坚持Event的模拟,而不是真实的实例。这是行不通的,因为正如例外所说,实体经理不识别模拟的类型为实体。

如果要编写集成测试,则应避免嘲笑并使用真实类而不是模拟。模拟更常用于独立于其他类别的单位测试。

Event event = new Event(); // Entity manager will recognize this as entity
...
et.begin();
em.persist(event);

相关内容

  • 没有找到相关文章