因此,我有UserService和UserInterface,其中有一个返回固定用户的方法。
public User currentUser(){
User user = new User();
user.setId(1L);
user.setName("Steve");
return user;
}
我还有一个RecipeService,getRecipe方法就在其中,我想测试一下,在这个方法中,我首先检查创建这个配方的用户的用户ID是否与currentUser ID相同,如果是,这个配方就返回给用户。
public Recipe getRecipe(Long id){
User user = userInterface.currentUser();
Recipe recipe = recipeRepository.findById(id);
if(user.getId == recipe.getUser.getId()){
return recipe;
}
return null;
}
所以我的测试看起来像这样:
class RecipeTest{
@InjectMock private RecipeService recipeService;
@Mock private RecipeRepository recipeRepository;
@Mock private UserInterface userInterface;
@BeforeEach
void setUp(){
recipeService = new RecipeService(userInterface);
}
@Test
void getRecipe(){
Recipe recipe = new Recipe();
recipe.setId(1L);
recipe.setTitle("SomeTitle");
when(recipeRepository.findById(1L)).thenReturn(Optional.of(recipe))
recipeService.getRecipe(1L);
verify(recipeRepository).findById(1L);
}
}
当我开始测试时,我得到一个错误,即在getRecipe方法中从UserInterface调用的currentUser为空(在if语句中比较ID时)。
你们能告诉我我做错了什么吗?
3条答案
按热度按时间yizd12fk1#
您使用空的mock模拟了接口
userInterface
。这没有任何作用。如果呼叫方法,您应该传回使用者对象:
0wi1tuuw2#
您正在模拟用户界面。您需要为currentUser()方法提供when().thenReturn()
wxclj1h53#
RecipeService行上似乎有错误,因为Mockito中没有@InjectMock注解。它应该是复数形式的@InjectMocks。
如果你想让一个方法返回一个固定的用户,你也应该在测试中模拟它,就像这样