3

Is there an equivalent in hamcrest library for JUnit's Assert#assertSame? If yes, what is it? At the moment I can only think of Hamcrest#sameInstance but I am not quite sure this method is the right one to use.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Arthur Eirich
  • 3,368
  • 9
  • 31
  • 63

2 Answers2

7

The underlying matcher that provides this functionality is 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.

Whichever you use is mainly a preference issue. Personally, I prefer statically importing from CoreMatchers, just because it's "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));
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

You want to turn to

assertThat(actual, isSame(expected))

here.

GhostCat
  • 137,827
  • 25
  • 176
  • 248