添加了@VisibleForTesting
和protected修饰符。我的测试现在可以使用该方法:
@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);
}
使用spy对象更新测试用例:然而,即使我创建了一个会被调用的spy对象的模拟,真正的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
,认为它可以帮助。并且我尝试使用spy。
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(...)
的访问修饰符更改为protected、package-private或public。 - liminal