【问题标题】:JUnit Assert#assertSame equivalent in HamcrestHamcrest 中的 JUnit Assert#assertSame 等效项
【发布时间】:2016-07-08 11:47:01
【问题描述】:

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

【问题讨论】:

    标签: java unit-testing junit instance hamcrest


    【解决方案1】:

    提供此功能的底层匹配器是org.hamcrest.core.IsSame。它有方便的方法将其隐藏在org.hamcrest.Matchers#sameInstance(如您所提到的)和org.hamcrest.CoreMatchers#sameInstance 中。

    您使用哪个主要是偏好问题。就个人而言,我更喜欢从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));
        }
    }
    

    【讨论】:

      【解决方案2】:

      你想转向

      assertThat(actual, isSame(expected))
      

      这里。

      【讨论】:

      • 有静态导入 org.hamcrest.Matchers.*; 我看到 无法解析方法 isSame。那我应该导入什么?
      • 你需要 CoreMatchers。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 2011-12-12
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多