简单的 `Assert.IsAssignableFrom` 失败
为什么这个简单的断言语句会失败?从我读到的内容来看,我应该是。不幸的是,由于该功能非常基础,因此没有太多信息。
public interface IDummy{}
public class Dummy : IDummy {}
Assert.IsAssignableFrom<IDummy>(new Dummy());
运行此测试会产生
Expected: assignable from <Application.Tests.ViewModels.IDummy>
But was: <Application.Tests.ViewModels.Dummy>
我尝试交换接口和对象端但无济于事。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IsAssignableFrom 的工作原理与您的期望相反。它询问:(值)是否可以从 IDummy 分配。或者:“可以分配给(值)吗?”
来自 XML 文档:
/// 断言可以为对象分配给定类型的值。
您可能需要 Assert.IsInstanceOfType()
IsAssignableFrom works in reverse from what you are expecting. It's asking: Is (the value) Assignable From IDummy. Or: "Is assignable to (value)?"
From the XML doc:
/// Asserts that an object may be assigned a value of a given Type.
You probably want Assert.IsInstanceOfType()
为了那些通过 Google(或 Bing :-) 登陆这里的人的利益)
Assert.IsAssignableFrom(objectactual)
旨在检查正在检查的对象是否可以用类型 T 替换实际上,这意味着断言正在测试所检查的对象与类型 T 之间的“is-a”关系让我们看一些代码(有意简化):
现在断言:
。 (objectactual) 旨在检查正在测试的对象是否是(顾名思义)类型 T 的实例 - 简而言之,如果“实际”是类型 T 还是从 T 派生的类型
编辑
事实证明,这些断言的工作方式与 系统.类型
For the benefit of those who land here through Google (or Bing :-) )
Assert.IsAssignableFrom<T>(object actual)
is meant to check if the object being examined can be substituted by the type T. Effectively, what this means is that the assertion is testing an "is-a" relationship between the object examined and the type T.Let's see some code (intentionally simplified):
Now the assertion:
Whereas the
IsInstanceOf<T>(object actual)
is meant to check whether the object being tested is (like the name suggests) an instance of type T - simply put, if "actual" is the type T or a type derived from TEDIT
Turns out, these asserts work the same way as Type.IsAssignableFrom and Type.IsInstanceOf methods on System.Type