How do I mock a @PrePersist method, e.g. preInit(), of an entity that I instantiate?
I'm using TestNG. EasyMock is prefered.
@Test(enabled = true)
public void testCreateOrder() {
// Instantiating the new mini order will automatically invoke the pre-persist method, which needs to be mocked/overwritten!
MiniOrder order = new MiniOrder();
order.setDate(new Date());
order.setCustomerId(32423423);
}
The MiniOrder.java is an entity that has a pre-persist method. Again, the one I like to mock/overwrite. E.g. this.id = 1
; Alternatively one could also mock the IdGenerator.getNewId()
method.
@PrePersist
protected void preInit(){
this.id = IdGenerator.getNewId();
}
I don't want the IdGenertor
class to be called, because it attempts to grab a jndi resource. I just don't understand how to capture this pre-persist method in advance, so that it's not triggered ,respectively replaced by different code, before the object is fully instantiaded.
In this case, what you really want is to mock the IdGenerator
dependency, which happens to be called from a @PrePersist
method.
Using JMockit, the test can be written as follows:
@Test
public void createOrder()
{
new MockUp<IdGenerator>() {
// change as needed...
@Mock int getNewId() { return 123; }
};
MiniOrder order = new MiniOrder();
order.setDate(new Date());
order.setCustomerId(32423423);
}