需要3个匹配器,1个重新编码-参数匹配器的使用无效-不涉及私有方法

x6492ojm  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(395)

我正在用mockito做junit测试。我在springboot应用程序中工作。被测试的类使用application.properties值。我已经包括了有关所涉及的类和测试中的方法的详细信息。当前应获得3个数学值,1个记录的异常。
应用程序属性

size=4
rate=0.5

项目服务

@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)))
}

项目存储库

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

项目服务测试

//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
}

无效使用MatcherException。我在这里看到了其他答案,但我不知道如何解决这个问题。被测试的方法只接受一个参数,但存根存储库有三个参数。我没有一些答案建议的任何私人方法。请告诉我该怎么解决这个问题。

r7xajy2e

r7xajy2e1#

最后我切换数值来测试结果。我补充了我的观察。

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

我相信这里提到的答案与我的情况有关。我不应该使用matchers参数调用测试中的实际方法,而是应该传递实际值。
对于存根法:

//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());

相关问题