我正在用Mockito编写一个测试类。我有一个类,它有一个返回另一个类的方法。
public BuilderClass build(){
return AnotherClass;
}当我用
assertThat(BuilderClass.build(), is(instanceOf(AnotherClass.class)));测试是可以的,但是当我使用
assertThat(BuilderClass.build(), is(sameInstance(AnotherClass.class)));测试是错误的。那么,使用instanceOf还是sameInstance有什么区别呢?
致以问候。
发布于 2016-05-18 07:49:43
来自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)));
}
}发布于 2016-05-18 07:53:29
sameInstance意味着这两个操作数是对同一个内存位置的引用。instanceOf测试第一个操作数是否真的是第二个操作数(类)的实例(对象)。
https://stackoverflow.com/questions/37293292
复制相似问题