我在我的 spring boot 项目中使用 spring data jpa。
我正在触发 JPQL 查询并使用投影来存储查询结果。
我的投影:
public interface VeryBasicProjection {
String getTitle();
String getUrl();
}
我的服务调用此投影:
public List<VeryBasicDTO> getLatestData(int limit){
// Pageable for Limit
Pageable pageable = new PageRequest(0, limit);
// Get Data from DB
List<VeryBasicProjection> latestData = tableRepository.getLatestData("live", 2,pageable);
List<VeryBasicDTO> responseDTO = new ArrayList<>();
// Map Projection to DTO
for(VeryBasicProjection veryBasicProjection : latestData){
VeryBasicDTO veryBasicDTO = new VeryBasicDTO();
veryBasicDTO.buildDTO(veryBasicProjection);
responseDTO.add(veryBasicDTO);
}
return responseDTO;
}
现在我想使用 Mockito(单元测试用例)测试这个服务
我在 mock 对存储库的调用
使用 when 和 thenReturn。
我的问题是如何模拟存储库的结果?那么应该返回什么?我的意思是如何为它创建投影实例和 setData ?
最佳答案
如果要创建投影实例而不创建实现接口(interface)的类,可以使用 SpelAwareProxyProjectionFactory。
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.projection.SpelAwareProxyProjectionFactory;
...
ProjectionFactory factory = new SpelAwareProxyProjectionFactory();
VeryBasicProjection projection = factory.createProjection(VeryBasicProjection.class);
projection.setTitle("theTitle");
projection.setUrl("theUrl");
您还需要在投影中添加 setter :
public interface VeryBasicProjection {
String getTitle();
String getUrl();
void setTitle(String title);
void setUrl(String url);
}
来源:https://github.com/spring-projects/spring-data-examples/blob/master/rest/projections/src/test/java/example/springdata/rest/projections/SimpleProjectionTests.java
关于mockito - 模拟投影结果 Spring Data JPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47258103/