首页 > 解决方案 > WrongTypeOfReturnValue:findById() 无法返回“对象”

问题描述

我正在尝试为我的 Spring Boot 应用程序进行测试,但我遇到了一个大问题。这就是我的错误的样子:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
WorkItem cannot be returned by findById()
findById() should return Optional

我正在关注教程,每个人都在使用findOne(),但对我来说它不起作用。我的 IDE 显示:

" 类型参数 'S' 的推断类型 'S' 不在其范围内;应扩展 'com.java.workitemservice.model.WorkItem"

这就是为什么我以另一种方式尝试并使用findById(),但后来又出现了另一个错误。

{ 
    @RunWith(SpringRunner.class)  
    @SpringBootTest  
    public class WorkitemServiceApplicationTests {  

    @Mock  
    private WorkItemRepository workItemRepository;

    @InjectMocks
             WorkItemsController workItemsController;

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

    @Test
    public void testGetUserById() {
    WorkItem workItem = new WorkItem();
    workItem.setId(1L);

    //old version
    //when(workItemRepository.findOne(1L)).thenReturn(workItem);
    when(workItemRepository.findById(1L).orElse(null)).thenReturn(workItem);

    WorkItem workItem2 = workItemsController.getWorkItemById(1L);

    verify(workItemRepository).findById(1L).orElse(null);

    assertEquals(1L, workItem2.getId().longValue());
    }
}

我的存储库:

    @Repository
    public interface WorkItemRepository extends JpaRepository<WorkItem, 
    Long> {

    Optional <WorkItem> findWorkItemBySubject(String subject);
    }

我的服务方式:

    public WorkItem getWorkItemById(Long id) {
    return this.workItemRepository.findById(id)
    .orElseThrow(() -> new 
    ResourceNotFoundException("WorkItem", "id", id));
    }

我的控制器方法:

    @GetMapping("/workItems/{id}")
    public WorkItem getWorkItemById(@PathVariable(value = "id") Long 
    workItemId) {

    return this.workItemService.getWorkItemById(workItemId);
    }
}

标签: javaspring-bootspring-data-jpamockito

解决方案


正如错误所述,您没有返回方法签名声明为返回类型的内容(即Optional<WorkItem>

刚回来

Optional.of(workitem) 

而不是workItem,即:

when(workItemRepository.findById(1L).orElse(null)).thenReturn(Optional.of(workitem));

推荐阅读