我正在尝试对我的 Spring boot 应用程序进行测试,但遇到了一个大问题。这就是我的错误的样子:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
WorkItem cannot be returned by findById()
findById() should return Optional
我正在遵循教程,每个人都在使用 findOne()
,但对我来说它不起作用。我的 IDE 显示:
" Inferred type 'S' for type parameter 'S' is not within its bound; should extend '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));
}
我的 Controller 方法:
@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));
关于java - 返回值类型错误 : "Object" cannot be returned by findById(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691476/