首页 > 解决方案 > 如何测试是否将正确的 lambda 值作为参数传递(使用 Mockito)?

问题描述

我有这个功能:

public class Cache {
    (...)
    public void removeAllIf(Predicate<Product> predicate) {
        (...)
    }
}

我打电话给productsCache.removeAllIf(Product::isChecked);

目前我用

then(productsCache).should().removeAllIf(any(Predicate.class));

但这不准确(不测试传递的 lambda 是否为Product::isChecked)。第二个问题是我收到 lint 消息:Unchecked assignment

它是更好的解决方案吗?

编辑:

我不想测试removeAllIf功能实现。我想测试是否removeAllIf使用正确的参数调用。

要测试的场景:

public class Repository {
    public void removeCheckedProducts() {
        remoteDataSource.removeCheckedProducts();
        localDataSource.removeCheckedProducts();
        cache.removeAllIf(Product::isChecked);

    }
}

单元测试:

@Test
public void removeCheckedProducts() {

    //when
    repository.removeCheckedProducts();

    //then
    then(remoteDataSource).should().removeCheckedProducts();
    then(localDataSource).should().removeCheckedProducts();
    then(cache).should().removeAllIf(any(Predicate.class));


}

标签: javaunit-testinglambdajava-8mockito

解决方案


您可以使用 ArgumentCaptor

@Captor
  ArgumentCaptor<Predicate> captor = ArgumentCaptor.forClass(Predicate.class);;

@Test
public void removeCheckedProducts() {

    //when
    repository.removeCheckedProducts();

    //then
    then(remoteDataSource).should().removeCheckedProducts();
    then(localDataSource).should().removeCheckedProducts();
    then(cache).should().removeAllIf(captor.capture());
    Predicate t = Product.checkPredicate();
    assertSame(t,captor.getValue());



}

推荐阅读