添加了 @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);
}
使用 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();
}
}
单独测试上述内容的最佳方法是什么?
非常感谢您的任何建议。
最佳答案
要防止真正的方法被调用使用:Mockito.doNothing().when(spy).onRecipeItem();
在这里你有最小的示例如何使用它:
public class ExampleUnitTest {
@Test
public void testSpyObject() throws Exception {
SpyTestObject spyTestObject = new SpyTestObject();
SpyTestObject spy = Mockito.spy(spyTestObject);
Mockito.doNothing().when(spy).methodB();
spy.methodA();
Mockito.verify(spy).methodB();
}
public class SpyTestObject {
public void methodA() {
methodB();
}
public void methodB() {
throw new RuntimeException();
}
}
关于java - 使用 Mockito 单独测试 Fragment 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44613144/