.NET 断言类型
有没有一种方法可以断言变量是否属于某种类型?
例如:
AssertIsBoolean(variable);
Is there a way that you can assert whether or not a variable is of a certain type?
Such as:
AssertIsBoolean(variable);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否真的试图断言变量属于特定类型,或者变量的值属于特定类型?
第一个不应该是单元测试的一部分 - 它是声明的代码的一部分。这就像尝试进行单元测试一样,您不能调用具有错误参数类型的方法。
第二个可以轻松完成
(假设
value
是object
类型的变量或接口。)请注意,这将测试兼容性而不是比确切的类型。如果您想测试某个值是否是精确类型,而不是子类型,您可以使用类似以下内容的内容:(
当然,在您使用的任何单元测试框架中都可能有可用于泛型方法的选项。)
Are you really trying to assert that a variable is of a particular type, or that the value of a variable is of a particular type?
The first shouldn't be part of a unit test - it's part of the declared code. It's like trying to unit test that you can't call a method with the wrong argument types.
The second can easily be accomplished with
(Assuming
value
is a variable of typeobject
or an interface.)Note that that will test for compatibility rather than the exact type. If you want to test that a value is an exact type, not a subtype, you might use something like:
(There may be options available for generic methods in whatever unit test framework you use, of course.)
您没有指定使用哪个测试框架。所以我想提一下 Gallio/MbUnit 测试框架为这一点提供了方便的断言目的:
You don't specify which testing framework you use. So I would like to mention that the Gallio/MbUnit testing framework provides a convenient assertion for that very purpose: