简体   繁体   English

spring JpaRepository方法的存根

[英]Stub of the spring JpaRepository method

I have next JPQL query: 我有下一个JPQL查询:

@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: 其中MeterData-只是投影接口:

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. 我不需要执行查询,但需要将其返回到MeterData列表。

How can I accomplish it? 我该怎么做? Should I create the Class implemented MeterData and instantiate it? 我应该创建并实现Class的MeterData吗? 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. 如果您需要对存储库进行存根以进行单元测试,请使用Mockito。 Declare your class implementation as private inner class in your test as you already did and instruct Mockito on using it: 像已经在测试中一样,将您的类实现声明为私有内部类,并指导Mockito使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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