Reputation: 991
When I try to mock class Event
with mock(Event.class)
I've got:
java.lang.IllegalArgumentException: Object: Mock for Event, hashCode: 640142691 is not a known entity type.
This is Event class:
@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 + " ]";
}
This is testing class:
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());
}
}
Anyone knows how to deal with that?
Upvotes: 1
Views: 834
Reputation: 15992
You are trying to persist a mock of Event
instead of a real instance of it. This won't work because, like the exception says, the entity manager doesn't recognize the type of the mock as entity.
If you want to write an integration test, you should avoid mocking and use your real classes instead of mocks. Mocks are more commonly used to make unit tests independent of other classes.
Event event = new Event(); // Entity manager will recognize this as entity
...
et.begin();
em.persist(event);
Upvotes: 2