当我尝试使用Event
模拟课程mock(Event.class)
时,我得到了:
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());
}
}
有谁知道如何处理?
答案 0 :(得分:2)
你试图坚持模仿Event
而不是真实的实例。这不起作用,因为,就像异常所说的那样,实体管理器不会将模拟的类型识别为实体。
如果你想编写集成测试,你应该避免嘲笑并使用真正的类而不是模拟。模拟更常用于独立于其他类别进行单元测试。
Event event = new Event(); // Entity manager will recognize this as entity
...
et.begin();
em.persist(event);