instanceOf 与 sameInstance
instanceOf vs sameInstance
我正在使用 Mockito 编写测试 class。我有一个 class 有一个方法可以 return 另一个 class
public BuilderClass build(){
return AnotherClass;
}
当我使用
assertThat(BuilderClass.build(), is(instanceOf(AnotherClass.class)));
测试没问题,但是当我使用
assertThat(BuilderClass.build(), is(sameInstance(AnotherClass.class)));
测试错误。那么,使用 instanceOf 或 sameInstance 有什么区别?
此致。
来自 javadoc
- 创建一个匹配器,仅当被检查的对象与指定的目标对象是同一实例时才匹配。
即两个指针link指向同一个内存位置。
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)));
}
}
sameInstance
表示两个操作数是对同一内存位置的引用。 instanceOf
测试第一个操作数是否真的是第二个操作数 (class) 的实例(对象)。
我正在使用 Mockito 编写测试 class。我有一个 class 有一个方法可以 return 另一个 class
public BuilderClass build(){
return AnotherClass;
}
当我使用
assertThat(BuilderClass.build(), is(instanceOf(AnotherClass.class)));
测试没问题,但是当我使用
assertThat(BuilderClass.build(), is(sameInstance(AnotherClass.class)));
测试错误。那么,使用 instanceOf 或 sameInstance 有什么区别?
此致。
来自 javadoc
- 创建一个匹配器,仅当被检查的对象与指定的目标对象是同一实例时才匹配。
即两个指针link指向同一个内存位置。
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)));
}
}
sameInstance
表示两个操作数是对同一内存位置的引用。 instanceOf
测试第一个操作数是否真的是第二个操作数 (class) 的实例(对象)。