如何测试findById方法



首先,我已经检查了以前关于这个问题的所有主题,但都没有帮助。

具有以下代码:

@DisplayName("GET RecipeUltraLight by id is successful")
@Test
public void givenRecipeId_whenGetRecipeDetailsById_thenReturnRecipeObject(){
// given
given(this.recipeRepository.findById(recipe.getId())).willReturn(Optional.of(recipe));
given(this.recipeService.getRecipeById(recipe.getId())).willReturn(recipe);
given(this.recipeConverter.toUltraLight(recipe)).willReturn(recipeUltraLightDto);
// when
RecipeUltraLightDto retrievedRecipe = recipeService.getRecipeUltraLightById(recipe.getId());
// then
verify(recipeRepository, times(1)).findById(recipe.getId());
verify(recipeService, times(1)).getRecipeById(recipe.getId());
verify(recipeConverter, times(1)).toUltraLight(recipe);
assertThat(retrievedRecipe).isNotNull();
}

给我这个错误:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Recipe cannot be returned by findById()
findById() should return Optional
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

服务方式:


@Transactional(readOnly = true)
public RecipeUltraLightDto getRecipeUltraLightById(Long id) {
Recipe recipe = getRecipeById(id);
RecipeUltraLightDto dto = new RecipeUltraLightDto();
dto = recipeConverter.toUltraLight(recipe);
return dto;
}
// internal use only
@Transactional(readOnly = true)
public Recipe getRecipeById(Long id) {
if (id == null || id < 1) {
return null;
}
return recipeRepository.findById(id)
.orElseThrow(() -> new RecipeNotFoundException(
String.format("Recipe with id %d not found.", id)
));
}

设置:

@ContextConfiguration(classes = {RecipeService.class})
@ExtendWith({SpringExtension.class, MockitoExtension.class})
class RecipeServiceTest {
@MockBean
private RecipeConverter recipeConverter;
@MockBean
private RecipeRepository recipeRepository;
@Autowired
private RecipeService recipeService;
private Recipe recipe;
private RecipeUltraLightDto recipeUltraLightDto;
@BeforeEach
public void setup(){
recipe = Recipe.builder()
.id(1L)
.name("Recipe")
.description("Description")
.createdAt(LocalDateTime.now())
.difficulty(RecipeDifficulty.EASY)
.minutesRequired(60)
.portions(4)
.authorId(1L)
.views(0)
.isVerified(false)
.build();

recipeUltraLightDto = RecipeUltraLightDto.builder()
.id(1L)
.name("Recipe")
.build();
}

我试过:

  1. 非线性光学((
  2. 正在添加.isPresent((
  3. 去掉.orElseThrow并执行if语句并使用.get((
  4. Kotlin

如果有人能帮忙,我会很高兴。

您正在创建测试对象的mock,这样基本上也会使存储库的mock变得毫无用处。

您应该删除行given(this.recipeService.getRecipeById(recipe.getId())).willReturn(recipe);,这样它只会调用方法并调用存储库。现在将返回模拟结果。因为这是现在将开始的行为。

其中明确提到,方法findById()返回Optional,需要通过调用Optional.get()来获得Recipe

最新更新