我正在使用Mockito编写测试类。我有一个类有一个方法来返回另一个类
public BuilderClass build(){
return AnotherClass;
}
当我使用
时assertThat(BuilderClass.build(), is(instanceOf(AnotherClass.class)));
测试没问题,但是当我使用
时assertThat(BuilderClass.build(), is(sameInstance(AnotherClass.class)));
测试错了。那么,使用 instanceOf 或 sameInstance 之间有什么不同?
问候。
答案 0 :(得分:3)
来自javadoc
即两个指针都链接到相同的内存位置。
Foo f1 = new Foo();
Foo f2 = f1;
assertThat(f2, is(sameInstance(f1)));
这是完整的测试:
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)));
}
}
答案 1 :(得分:3)
sameInstance
表示两个操作数是对同一内存位置的引用。 instanceOf
测试第一个操作数是否真的是第二个操作数(类)的实例(对象)。