java-模拟休眠会话

我正在尝试模拟休眠会话.这是我尝试过的代码片段:

@Before
public void setUp() {
    campaignModel = DraftTestHelper.buildDraftModel();
    if(sessionFactory != null) {
        System.out.println("Session Factory not null");
    }
    else
        System.out.println("Session Factory is null");
    session = sessionFactory.getCurrentSession();

    if(session != null) {
        System.out.print("Not null");
    }
    else 
        System.out.println("Null");

}

模拟代码:

@Mock
SessionFactory sessionFactory;

@InjectMocks
DraftCampaignModelBuilder draftBuilder;  

private DraftCampaignModel campaignModel;
private Session session;

根据控制台,会话工厂不为空.但是休眠会话为空.有人可以帮忙吗?

谢谢

解决方法:

我认为您需要在@Before方法中编写以下代码:

when(sessionFactory.getCurrentSession()).thenReturn(hibernateSession);

例如

@Mock
private HibernateSession hibernateSession;

@Before
public void setUp() {
    when(sessionFactory.getCurrentSession()).thenReturn(hibernateSession);

    campaignModel = DraftTestHelper.buildDraftModel();
    if(sessionFactory == null) {
        System.out.println("Session Factory is null");
    }
    else {
        System.out.println("Session Factory is not null");
        session = sessionFactory.getCurrentSession();

        if(session != null) {
            System.out.print("Session is not null");
        }
        else {
            System.out.println("Session is null");
        }
    }
}
上一篇:创建一个采用Java参数的模拟对象


下一篇:android-robolectric-如何在创建Activity对象时模拟和注入业务类