0

I am programming a test class using Mockito. I have a class that has a method to return another class

public BuilderClass build(){
     return AnotherClass;
}

When I use

assertThat(BuilderClass.build(), is(instanceOf(AnotherClass.class)));

The test is ok but when I use

assertThat(BuilderClass.build(), is(sameInstance(AnotherClass.class)));

The test is wrong. So, What is the different between use instanceOf or sameInstance?

Regards.

Chema
  • 67
  • 4
  • 17
  • A bit off-topic but please see: http://stackoverflow.com/questions/2790144/avoiding-instanceof-in-java When you use multiple instanceof in your code it can be considered as a "smell", the use of reflection can clean this up. – M. Suurland May 18 '16 at 07:51
  • Thank you for off-topic. I didn't know about this situation. – Chema May 18 '16 at 08:34

2 Answers2

3

From javadoc

  • Creates a matcher that matches only when the examined object is the same instance as the specified target object.

Ie both pointers link to the same memory location.

Foo f1 = new Foo();
Foo f2 = f1;
assertThat(f2, is(sameInstance(f1)));

Here is the complete test:

public class FooTest {

class Foo {

}

private Foo f1 = new Foo();
private Foo f2 = new Foo();

/**
 * Simply checks that both f1/f2 are instances are of the same class
 */
@Test
public void isInstanceOf() throws Exception {
    assertThat(f1, is(instanceOf(Foo.class)));
    assertThat(f2, is(instanceOf(Foo.class)));
}

@Test
public void notSameInstance() throws Exception {
    assertThat(f2, not(sameInstance(f1)));
}

@Test
public void isSameInstance() throws Exception {
    Foo f3 = f1;
    assertThat(f3, is(sameInstance(f1)));
}
}
inigo skimmer
  • 908
  • 6
  • 12
3

sameInstance means that the two operands are references to the same memory location. instanceOf tests if the first operand is really an instance (object) of the second operand (class).

AhmadWabbi
  • 2,253
  • 1
  • 20
  • 35