简体   繁体   中英

Stub of the spring JpaRepository method

I have next JPQL query:

@Query(value = "select t.ts as ts, t.ko.eolink.guid as guid from ObjPar t "
        + "where t.tuser.cd = ?1 and t.lst.cd=?2 and t.ts between ?3 and ?4")
List<MeterData> findTimestampByUser(String userCd, String lstCd, Date dtFrom, Date dtTo);

where MeterData - is just projection interface:

public interface MeterData {
    Date getTs();
    String getGuid();
}

Now I need to write something like a stub. I don't need to my query to be executed, but I need it to be returned the List of MeterData.

How can I accomplish it? Should I create the Class implemented MeterData and instantiate it? May be somebody could hint me more simple approach?

My solution:

List<MeterData> findTimestampByUser(String userCd, String lstCd, Date dtFrom, Date dtTo) {

        class LocalMeterData implements MeterData {
            public Date getTs() {
                return new Date();
            }
            public String getGuid() {
                return "2312-1316-4564-4654-4463";
            }
        }

        List<MeterData> lst = new ArrayList<>(5);
        MeterData elem = new LocalMeterData();
        lst.add(elem);
        lst.add(elem);
        lst.add(elem);
        lst.add(elem);

return lst;

}

If you need to stub your repository for unit test just use Mockito. Declare your class implementation as private inner class in your test as you already did and instruct Mockito on using it:

MeterData elem = new LocalMeterData();
Mockito.when(yourRepository.findTimestampByUser(anyString(), any(Date.class), any(Date.class)))
        .thenReturn(Arrays.asList(elem, elem, elem, elem));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM