How to mock @PrePersist method?

故事扮演 提交于 2021-01-27 11:50:23

问题


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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/24673150/how-to-mock-prepersist-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!