I am doing an mvc test in my program that the getRecipes() method is supposed to return a list of recipes. Also, the Recipe class has not overridden the equals method and the hashCode.
As it is known in the RecipeService class, a new HashSet is returned every time, but recipes which is in it is the same because its repository is the same. Therefore, we should expect to receive a different HashSet but the same recipe with each call to the getRecipes method, so when calling equals on the hash sets, it should return true because they have the same content, but surprisingly When runnig, we see that these two hash sets have different recipes!
@SpringBootTest
class RecipeControllerTest {
@Mock
private Model model;
@Autowired
private RecipeService recipeService;
@Autowired
private RecipeController recipeController;
@Test
public void testMVC() {
try {
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(recipeController).build();
mockMvc.perform(MockMvcRequestBuilders.get("/"))
.andExpect(status().isOk())
.andExpect(model().attribute("recipes", recipeService.getRecipes()))
.andExpect(view().name("index"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
RecipeService class:
public class RecipeService {
private final RecipeRepository recipeRepository;
public RecipeService(RecipeRepository recipeRepository) {
this.recipeRepository = recipeRepository;
}
public Set<Recipe> getRecipes(){
log.debug("debugging message inside of "+getClass().getSimpleName());
Set<Recipe> recipes=new HashSet<>();
recipeRepository.findAll().forEach(recipes::add);
return recipes;
}
}
error:
java.lang.AssertionError: Model attribute 'recipes' expected:<[com.arbabsoft.recipe.model.Recipe@4619854a]> but was:<[com.arbabsoft.recipe.model.Recipe@6eff05e7]>
Expected :[com.arbabsoft.recipe.model.Recipe@4619854a]
Actual :[com.arbabsoft.recipe.model.Recipe@6eff05e7]
But when I apply the following changes to the RecipeControllerTest class, the test passes.
@Mock
private RecipeService recipeService;
@InjectMocks
private RecipeController recipeController;
What is the reason for this? Did JUnit, Mockito and spring MVC test conflict?