Hamcrest 中的 JUnit Assert#assertSame 等价物

JUnit Assert#assertSame equivalent in Hamcrest

在 hamcrest 库中是否有 JUnit Assert#assertSame 的等价物?如果是,那是什么?目前我只能想到Hamcrest#sameInstance,但我不太确定这种方法是否正确。

您想转到

assertThat(actual, isSame(expected))

这里。

提供此功能的底层匹配器是 org.hamcrest.core.IsSame. It has convenience methods to hide it both in org.hamcrest.Matchers#sameInstance (as you mentioned) and in org.hamcrest.CoreMatchers#sameInstance

用哪个主要是喜好问题。就个人而言,我更喜欢从 CoreMatchers 静态导入,只是因为它是 "slimmer":

import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertThat;

import org.junit.Test;

public class SomeTest {
    @Test
    public void testSomething() {
        Object o1 = new Object();
        Object o2 = o1;

        assertThat(o1, sameInstance(o2));
    }
}