【发布时间】:2017-11-20 15:24:02
【问题描述】:
添加了@VisibleForTesting 并受到保护。我的测试现在可以这个方法了:
@VisibleForTesting
protected void setupDataBinding(List<Recipe> recipeList) {
recipeAdapter = new RecipeAdapter(recipeList);
RecyclerView.LayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
rvRecipeList.setLayoutManager(layoutManager);
rvRecipeList.setAdapter(recipeAdapter);
}
使用间谍对象更新了测试用例:但是,即使我创建了一个将被调用的间谍模拟,真正的 setupDataBinding(recipe) 也会被调用。也许我做错了。
@Test
public void testShouldGetAllRecipes() {
RecipeListView spy = Mockito.spy(fragment);
doNothing().when(spy).setupDataBinding(recipe);
fragment.displayRecipeData(recipe);
verify(recipeItemClickListener, times(1)).onRecipeItemClick();
}
我正在尝试测试我的Fragment 类中的方法,如下所示。但是,我试图模拟这些方法以验证这些方法被正确调用的次数。但是,问题是我有一个private 方法setupDataBinding(...),它设置在从displayRecipeData(...) 调用的RecyclerView 上。我想模拟这些调用,因为我不想在RecyclerView 上调用真实对象。我只是想验证 setupDataBinding(...) 是否被调用。
我尝试过使用 spy 和 VisibleForTesting,但仍然不知道该怎么做。
我正在尝试单独测试 Fragment。
public class RecipeListView
extends MvpFragment<RecipeListViewContract, RecipeListPresenterImp>
implements RecipeListViewContract {
@VisibleForTesting
private void setupDataBinding(List<Recipe> recipeList) {
recipeAdapter = new RecipeAdapter(recipeList);
RecyclerView.LayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
rvRecipeList.setLayoutManager(layoutManager);
rvRecipeList.setAdapter(recipeAdapter);
}
@Override
public void displayRecipeData(List<Recipe> recipeList) {
/* Verify this get called only once */
setupDataBinding(recipeList);
recipeItemListener.onRecipeItem();
}
}
这就是我正在测试的方式。我添加了VisibleForTesting 认为我可以提供帮助。我尝试过使用间谍。
public class RecipeListViewTest {
private RecipeListView fragment;
@Mock RecipeListPresenterContract presenter;
@Mock RecipeItemListener recipeItemListener;
@Mock List<Recipe> recipe;
@Before
public void setup() {
MockitoAnnotations.initMocks(RecipeListViewTest.this);
fragment = RecipeListView.newInstance();
}
@Test
public void testShouldGetAllRecipes() {
fragment.displayRecipeData(recipe);
RecipeListView spy = Mockito.spy(fragment);
verify(recipeItemListener, times(1)).onRecipeItem();
}
}
单独测试上述内容的最佳方法是什么?
非常感谢您的建议。
【问题讨论】:
-
添加
@VisibleForTesting是不够的。您还必须将setupDataBinding(...)的访问修饰符更改为受保护的、包私有的或公共的。 -
@liminal 我已经用我最近的尝试更新了我的问题。即使我创建了它的间谍对象,我也未能阻止调用真正的方法。
标签: java android unit-testing mockito android-testing