当前位置: 代码迷 >> java >> WrongTypeOfReturnValue:findById()无法返回“对象”
  详细解决方案

WrongTypeOfReturnValue:findById()无法返回“对象”

热度:45   发布时间:2023-07-31 11:55:47.0

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

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);
    }
}

由于错误状态,您没有返回方法签名声明为返回类型的值(这是Optional<WorkItem> )。

刚回来

Optional.of(workitem) 

代替workItem ,即:

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

您在调用findbyId()时需要添加方法get()仓库中的大多数方法都返回一个可选的

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

我在评论中看到您尝试了此操作:

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

它应该正在工作。 我认为问题出在您的“ orElse”电话上。

确切地说,这是以下情况下的方法:

public static <T> OngoingStubbing<T> when(T methodCall) {
        return MOCKITO_CORE.when(methodCall);
    }

因此,我认为使用“ orElse”可以防止推断出“ T”。

我的问题是为什么要使用“ orElse”? 您正在使用该方法。

您可以使用“ anyString”来匹配任何参数。

干杯