编程语言
首页 > 编程语言> > java-模拟休眠会话

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

标签:hibernate,mockito,powermock,session,java
来源: https://codeday.me/bug/20191111/2022795.html