Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WrongTypeOfReturnValue: "Object" cannot be returned by findById()

I am trying to do tests for my Spring boot application, and I've got a big problem. This is how my error looks like:

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

I was following tutorials and everyone is using findOne(), but for me it just doesn't work. My IDE shows:

" Inferred type 'S' for type parameter 'S' is not within its bound; should extend 'com.java.workitemservice.model.WorkItem"

That's why I tried it the other way and used findById(), but then I got another error.

{ 
    @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());
    }
}

My Repository :

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

    Optional <WorkItem> findWorkItemBySubject(String subject);
    }

My service method:

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

My Controller method :

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

    return this.workItemService.getWorkItemById(workItemId);
    }
}
like image 693
sokoler Avatar asked Sep 05 '25 21:09

sokoler


1 Answers

As the error states, you are not returning what the method signature declares as a return type (which is Optional<WorkItem>)

Just return

Optional.of(workitem) 

instead of workItem, i.e :

when(workItemRepository.findById(1L).orElse(null)).thenReturn(Optional.of(workitem));
like image 83
Arnaud Avatar answered Sep 08 '25 10:09

Arnaud