Added by @VisibleForTesting and is protected. My test can now be as follows:
@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); }
A test case using the spy object has been updated: however, the real setupDataBinding (recipe) is called even when I created the layout of its spy, which will be called. Maybe I'm doing it wrong.
@Test public void testShouldGetAllRecipes() { RecipeListView spy = Mockito.spy(fragment); doNothing().when(spy).setupDataBinding(recipe); fragment.displayRecipeData(recipe); verify(recipeItemClickListener, times(1)).onRecipeItemClick(); }
I am trying to test methods in my Fragment class as shown below. However, I am trying to make fun of methods to verify that the methods are called the correct number of times. However, the problem is that I have a private setupDataBinding(...) method that is configured with a RecyclerView that is called from displayRecipeData(...) . I want to mock these calls because I don’t want to name the real object on RecyclerView . I just want to check what the setupDataBinding(...) call is.
I tried using spy and VisibleForTesting , but still not sure how to do this.
I am trying to test a fragment in isolation.
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) { setupDataBinding(recipeList); recipeItemListener.onRecipeItem(); } }
This is how I test. I added a VisibleForTesting thinking that I could help you. And I tried to use a 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(); } }
What would be the best way to verify the above?
Thanks so much for any advice.