So I have UserService and UserInterface, where there is a method that returns a fixed user.
public User currentUser(){
User user = new User();
user.setId(1L);
user.setName("Steve");
return user;
}
I also have a RecipeService, where the getRecipe method is located, which I want to test. In this method, I first check if the user ID of the user who created the recipe is the same as the currentUser ID. If yes, the recipe is returned to the user.
public Recipe getRecipe(Long id){
User user = userInterface.currentUser();
Recipe recipe = recipeRepository.findById(id);
if(user.getId == recipe.getUser.getId()){
return recipe;
}
return null;
}
So my test looks like this:
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);
}
}
When I start the test, Im getting error that currentUser that is called from UserInterface in the getRecipe method is null (when comparing IDs in the if statment). It looks like the method currentUser() is not called.
Can you guys tell me what am I doing wrong?