Art*_*ich 2 java junit unit-testing instance hamcrest
JUnit 的 hamcrest 库中是否有等价物Assert#assertSame?如果是,那是什么?目前我只能想到Hamcrest#sameInstance但我不太确定这种方法是否适合使用。
提供此功能的底层匹配器是org.hamcrest.core.IsSame. 它有方便的方法可以将它隐藏在org.hamcrest.Matchers#sameInstance(如您所提到的)和org.hamcrest.CoreMatchers#sameInstance.
无论您使用哪个主要是偏好问题。就个人而言,我更喜欢静态导入 from CoreMatchers,只是因为它“更苗条”:
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));
}
}
Run Code Online (Sandbox Code Playgroud)