NUnit 中的 TypeOf 和 InstanceOf 有什么区别?
What is the difference between TypeOf and InstanceOf in NUnit?
在NUnit
中,Is.TypeOf
和Is.InstanceOf
有什么区别?
在下面的示例中,我注意到它们都是 return true:
public class Foo
{
public Boo GetBoo()
{
return new Boo();
}
}
public class Boo { }
和NUnit
测试方法:
[Test]
public void GetBoo_WhenCalled_ReturnBoo
{
var foo = new Foo();
var result = foo.GetBoo();
Assert.That(result, Is.TypeOf<Boo>()); //return true
Assert.That(result, Is.InstanceOf<Boo>()); //return true
}
documentation有点难理解:
TypoOf
- tests that an object is an exact Type.
InstanceOf
- tests that an obect is an instance of a Type
这意味着与 TypoOf
相比,InstanceOf
也将测试导数。
所以,在下面的例子中:
public class Foo
{
public Boo GetBoo()
{
return new Woo();
}
}
public class Woo : Boo { }
测试方法:
[Test]
public void GetBoo_WhenCalled_ReturnBoo()
{
var foo = new Foo();
var result = foo.GetBoo();
Assert.that(result, Is.TypeOf<Boo>()); // False ("Boo")
Assert.that(result, Is.InstanceOf<Boo>()); //True ("Boo" or "Woo")
}
TypeOf
将 return false 导致它检查结果类型是否仅为 Boo
。
InstanceOf
将 return 为真,因为它检查结果类型是 Boo
还是 Woo
.
在NUnit
中,Is.TypeOf
和Is.InstanceOf
有什么区别?
在下面的示例中,我注意到它们都是 return true:
public class Foo
{
public Boo GetBoo()
{
return new Boo();
}
}
public class Boo { }
和NUnit
测试方法:
[Test]
public void GetBoo_WhenCalled_ReturnBoo
{
var foo = new Foo();
var result = foo.GetBoo();
Assert.That(result, Is.TypeOf<Boo>()); //return true
Assert.That(result, Is.InstanceOf<Boo>()); //return true
}
documentation有点难理解:
TypoOf
- tests that an object is an exact Type.
InstanceOf
- tests that an obect is an instance of a Type
这意味着与 TypoOf
相比,InstanceOf
也将测试导数。
所以,在下面的例子中:
public class Foo
{
public Boo GetBoo()
{
return new Woo();
}
}
public class Woo : Boo { }
测试方法:
[Test]
public void GetBoo_WhenCalled_ReturnBoo()
{
var foo = new Foo();
var result = foo.GetBoo();
Assert.that(result, Is.TypeOf<Boo>()); // False ("Boo")
Assert.that(result, Is.InstanceOf<Boo>()); //True ("Boo" or "Woo")
}
TypeOf
将 return false 导致它检查结果类型是否仅为 Boo
。
InstanceOf
将 return 为真,因为它检查结果类型是 Boo
还是 Woo
.