在Hibernate中使用addScalar属性对SQLQuery进行Mockito测试

时间:2018-10-23 07:14:47

标签: mockito junit4

我在studentResultHibernateDao中有一个方法

@Override
public Map<String, Object> getStudentResultByNameAndId(String name ,String id, Number batchId) {
    final String queryString =  " select id , tracking_type_id , date_created from STUDENT_RESULT_INFO "+
             " where name = '" + name + "' and  batch_id = "+batchId  +  " and tracking_type_id in (1,2) " ;

    SQLQuery sq = sessionFactory.getCurrentSession().createSQLQuery(queryString);
    sq.addScalar("id", StringType.INSTANCE);
    sq.addScalar("tracking_type_id",StringType.INSTANCE);
    sq.addScalar("date_created", TimestampType.INSTANCE);
    sq.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
    List<Map<String, Object>> resultSet = sq.list();
    Map<String, Object> trackingInfo = new HashMap<String, Object>();
    for (Map<String, Object> resultMap : resultSet) {
        trackingInfo.put((String) resultMap.get("id") + "-" + (String) resultMap.get("tracking_type_id"),(Timestamp) resultMap.get("date_created"));
    }
    return trackingInfo;
}

对于getStudentResultByNameAndId方法,我正在尝试编写一个jUnit测试:以下是到目前为止我尝试过的代码。

在StudentResultHibernateDaoTest.java

@RunWith(MockitoJUnitRunner.class)
public class StudentResultHibernateDaoTest {

@Mock
private Log log;

@Mock
private SessionFactory sessionFactory;

@Mock
private Session session;

@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();

@InjectMocks
private StudentResultHibernateDao studentResultHibernateDao;

@Before
public void beforeTest(){
    MockitoAnnotations.initMocks(this);
}

@Test
public void  testGetStudentResultByNameAndId() {
    String name = "fgafsg@gmail.com";
    Number batchId = 23;
    List<StudentInfoTest> studentInfoList = new ArrayList<>(1);

    Session session = Mockito.mock(Session.class);
    Query query = Mockito.mock(Query.class);
    Mockito.when(sessionFactory.getCurrentSession()).thenReturn(session);
    Mockito.when(session.createQuery(" select id , tracking_type_id , date_created from STUDENT_RESULT_INFO "+
             " where name = '" + name + "' and  batch_id = "+batchId  +  " and tracking_type_id in (1,2) ")).thenReturn(query);
    //how to add "sq.addScalar" in mockito as in above code.
    Mockito.when(query.list()).thenReturn(studentInfoList);
}

在StudentInfoTest.java

public class StudentInfoTest{
  // should i create a model class as normally? what should i do here
}

以上实现对sqlQueries的junit测试是否正确?如何在Mockito中向SQL查询添加标量属性?

0 个答案:

没有答案