java - 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);
}
}
解决方案
正如错误所述,您没有返回方法签名声明为返回类型的内容(即Optional<WorkItem>
)
刚回来
Optional.of(workitem)
而不是workItem
,即:
when(workItemRepository.findById(1L).orElse(null)).thenReturn(Optional.of(workitem));
推荐阅读
- flutter - 在 Flutter DropdownButtonFormField 中获取多个值
- c++ - 为什么 fftw 在 vscode 中总是未定义的引用?
- docker - Docker - 无论框架如何设置多个项目(在 php 上)
- c# - Shaded pictures on focused item in collection view
- python - 最多 X 个值的平均值,然后与最后一个值取平均值?
- c# - linq: from object in an object to just an object
- javascript - 如何使用 Chart.js 创建这样的条形图?
- c# - 更新 CollectionView
- javascript - 如何使用 rxjs 从 json 对象中过滤属性?
- python-3.x - 如何转换
“二进制字符串”到 b“二进制字符串”?