两个确切的方法参考不相等 [英] Two exact method references are not equal

查看:90
本文介绍了两个确切的方法参考不相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下测试失败

@Test
public void test() {
    Function<String, Integer> foo = Integer::parseInt;
    Function<String, Integer> bar = Integer::parseInt;
    assertThat(foo, equalTo(bar));
}

有没有办法让它通过?

编辑:我会尝试更清楚地说明我要做的事情。

edit: I'll try to make it more clear what I'm trying to do.

让我们看看说我有这些课程:

Lets say I have these classes:

class A {
  public int foo(Function<String, Integer> foo) {...}
}

class B {
  private final A a; // c'tor injected
  public int bar() {
    return a.foo(Integer::parseInt);
  }
}

现在可以说我想为B编写单元测试:

now lets say i want to write unit test for B:

@Test
public void test() {
  A a = mock(A.class);
  B b = new B(a);
  b.bar();
  verify(a).foo(Integer::parseInt);
}

问题是测试失败,因为方法引用不相等。

the problem is that the test fails, because the method references are not equal.

推荐答案

Lambda不会被缓存,这似乎是故意的。没有办法比较两个lambdas,看看他们是否会做同样的事情。

Lambdas are not cached and this seems to be deliberate. There is no way to compare two lambdas to see if they would do the same thing.

你需要做类似的事情

static final Function<String, Integer> parseInt = Integer::parseInt;

@Test
public void test() {
    Function<String, Integer> foo = parseInt;
    Function<String, Integer> bar = parseInt;
    assertThat(foo, equalTo(bar));
}

来自Brian Goetz的回答; 有没有办法比较lambdas?

Answer from Brian Goetz; Is there a way to compare lambdas?

这篇关于两个确切的方法参考不相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆