0

I am doing Junit test with Mockito. I am working in a Springboot application. The class under test uses application.properties values. I have included details about the class involved and the method under test. Currently getting 3 mathcers expected, 1 recorded exception.

application.properties

size=4
rate=0.5

ItemService

@Value("${size}");
private String size;
@Value("${rate}")
private String rate
....................
.............


//debugging mode show me rate and size are null when it reach this point
//added ReflectionTestUtils, and set rate and size fields for test
public List<Item> getAllItems(final int id) {
    return repository.findAllItems(id, Integer.parseInt(rate),  PageRequest.of(0,Integer.parseInt(size)))
}

ItemRepository

@Query("SELECT......")
List<Item> findAllItems(@Param("id") id, @Param("rate") int rate, @Param("size") int size);

ItemServiceTest

//I did not have any class level annotation
public class ItemServiceTest {
@InjectMocks
public ItemService service;
@Mock
public ItemRepository repo

@Before
public void setUp() throws Exception {

    MockitoAnnotations.initMocks(this);
}

@Test 
void getAllItems_has_data() {
ReflectionTestUtils.setField(service, "size", "4");
ReflectionTestUtils.setField(service, "rate", "0.35");
Mockito.when(repo.findAllItems(Mockito.anyInt(), Mockito.anyInt(),   Mockito.any(Pageable.class))).thenReturn(getItemsData());

//Invalid use of argument matchers! 3 matchers expected, 1 recorded
List<Items> itemList = service.getAllItems(Mockito.anyInt());
Asserttions.assertThat(itemList.get(0)).isNotNull();

}

}

//mock data method
public List<Item> getItemsData() {
    ..............
    ...............
    return items
}

InvalidUseOfMatchersException. I have seen other answers here, but I could not figure out how to fix this issue. The method under test takes only one argument, but stubbed repository has three arguments it is taking. I do not have any private methods as suggested by some answers. Please I need some direction to solve this.

user1986244
  • 259
  • 2
  • 12

1 Answers1

1

I end up switching values to test the outcome. I have added my observation.

//replaced Mockito.anyInt() with actual/raw value solved my issue
List<Items> itemList = service.getAllItems(3);

I believe the stackoverflow answer mentioned here relates to my situation. I should not call actual method under test with matchers argument, but instead I should pass actual values.

For stubbed method:

//this line remain the same, but replacing the first two argument with actual/raw
//values will generate similar exception "3 matchers expected, 1 recorded". 
// we should not combine matchers with raw values
Mockito.when(repo.findAllItems(Mockito.anyInt(), Mockito.anyInt(), Mockito.any(Pageable.class))).thenReturn(getItemsData());
user1986244
  • 259
  • 2
  • 12