Reputation: 33
I have found that there are different results when using mockito matchers anyList() and any(List.class). I can not unterstand this, however, since both should actually return the same result. Maybe someone can enlighten me.
I use the matcher to test a controller. My controller binds an attribute to the model called myList. I want to verify that the model attribute is actually a list.
model.addAttribute("myList", Arrays.asList("test"));
any(List.class) performs a correct test:
mockMvc.perform(get("/")).andExpect(model().attribute("myList", any(List.class)));
But anyList() returns that [] was expected and causes a test failure:
mockMvc.perform(get("/")).andExpect(model().attribute("myList", anyList()));
I need anyListOf(String.class) to verify that the list contains strings, but I can not use it because of this behavior.
Upvotes: 1
Views: 6061
Reputation: 691785
You're using ModelResultMatchers.attribute()
, which checks that the model attribute named "myList" is equal to the second argument, i.e. is equal to the value returned by any(List.class)
or anyList()
.
Note that this method doesn't expect a Mockito matcher at all. It isn't even related to Mockito at all. It just expects a value, and checks that the model attribute is equal to this value.
anyList()
returns a new empty ArrayList. any(List.class)
returns null. So your first test succeeds because your controller happens to store null in this model attribute, and your second test fails because null is not equal to an empty ArrayList.
TL;DR: you shouldn't use Mockito matchers here. That makes no sense.
Upvotes: 4