【发布时间】:2019-07-08 13:02:15
【问题描述】:
我正在尝试对我的 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);
}
}
【问题讨论】:
标签: java spring-boot spring-data-jpa mockito