【问题标题】:Unit testing method with method reference as parameter以方法引用为参数的单元测试方法
【发布时间】:2018-11-08 04:05:39
【问题描述】:

我有一个方法,它将一个对象和一个对该对象的方法引用作为参数,以从该对象收集集合中的整数。代码运行良好,但我无法在 when() 方法上使用 mockito 进行单元测试。

public class UserCredentials {

  private Integer accountId;

  private Integer customerNameId;
}

public class UserCredentialsUtil {

  public List<Integer> userCredentialsGetter(
      final List<UserCredentials> userCredentials,
      final Function<UserCredentials, Integer> func) {
    return userCredentials.stream().map(func).collect(Collectors.toList());
  }
}

我的单元测试基本上返回给我一个空列表。

  @Mock
  private UserCredentialsUtil userCredentialsUtil;

final List<Integer> accountIds = Arrays.asList(1, 2, 3);

        when(
        this.userCredentialsUtil.userCredentialsGetter(
            userCredentials,
         UserCredentials::getAccountId)).thenReturn(accountIds);

我知道这不是我的设置问题,因为如果我将 UserCredentialsGetter 更改为

  public List<Integer> userCredentialsGetter(
      final List<UserCredentials> userCredentials) {
    return userCredentials.stream().map(UserCredentials::getAccountId).collect(Collectors.toList());
  }

以及测试方法。

        when(
        this.userCredentialsUtil.userCredentialsGetter(
            userCredentials)).thenReturn(accountIds);

这很好用。我猜我需要传递其他东西,然后是方法引用作为我第一次测试的参数,但我很不幸地发现其他人进入这个案例,即使它看起来很常见。

【问题讨论】:

    标签: java unit-testing mockito


    【解决方案1】:

    使用 mockito,您需要确保传入 when 语句的方法与实际方法传入的方法相同。根据您的示例,您使用的是 UserCredentials::getAccountIdUserCredentials::accountId(可能是错字)。

    您可能需要考虑使用不同的参数匹配器:

    import static org.mockito.ArgumentMatchers.*;
    
    when(userCredentialsUtil.userCredentialsGetter(eq(userCredentials), any()).thenReturn(accountIds);
    

    【讨论】:

    • 是的错字对不起。也许匹配器会这样做。
    • 很高兴我能帮上忙! :)
    猜你喜欢
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 2022-07-02
    • 2017-06-10
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多