mockito 如何测试一个依赖于来自不同服务的另一个方法的方法?

ddrv8njm  于 2022-11-08  发布在  其他
关注(0)|答案(3)|浏览(165)

因此,我有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时)。
你们能告诉我我做错了什么吗?

yizd12fk

yizd12fk1#

您使用空的mock模拟了接口userInterface。这没有任何作用。
如果呼叫方法,您应该传回使用者对象:

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(userInterface.currentUser()).thenReturn(new User())
        when(recipeRepository.findById(1L)).thenReturn(Optional.of(recipe))

        recipeService.getRecipe(1L);
        verify(recipeRepository).findById(1L);
      } 
    }
0wi1tuuw

0wi1tuuw2#

您正在模拟用户界面。您需要为currentUser()方法提供when().thenReturn()

wxclj1h5

wxclj1h53#

RecipeService行上似乎有错误,因为Mockito中没有@InjectMock注解。它应该是复数形式的@InjectMocks。
如果你想让一个方法返回一个固定的用户,你也应该在测试中模拟它,就像这样

when(UserInterface.currentUser()).thenReturn(new User());

相关问题