.NET 断言类型

发布于 2024-10-01 10:03:19 字数 94 浏览 1 评论 0原文

有没有一种方法可以断言变量是否属于某种类型?

例如:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

可爱咩 2024-10-08 10:03:20

您是否真的试图断言变量属于特定类型,或者变量的属于特定类型?

第一个不应该是单元测试的一部分 - 它是声明的代码的一部分。这就像尝试进行单元测试一样,您不能调用具有错误参数类型的方法。

第二个可以轻松完成

Assert.IsTrue(value is bool);

(假设valueobject类型的变量或接口。)

请注意,这将测试兼容性而不是比确切的类型。如果您想测试某个值是否是精确类型,而不是子类型,您可以使用类似以下内容的内容:(

Assert.AreEqual(typeof(ArgumentException), ex.GetType());

当然,在您使用的任何单元测试框架中都可能有可用于泛型方法的选项。)

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

Assert.IsTrue(value is bool);

(Assuming value is a variable of type object 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:

Assert.AreEqual(typeof(ArgumentException), ex.GetType());

(There may be options available for generic methods in whatever unit test framework you use, of course.)

滥情稳全场 2024-10-08 10:03:20
if(myValue is Boolean)
{

}
if(myValue is Boolean)
{

}
鸢与 2024-10-08 10:03:20
Assert.IsTrue(variable is bool, "variable was not a Boolean Value");
Assert.IsTrue(variable is bool, "variable was not a Boolean Value");
木槿暧夏七纪年 2024-10-08 10:03:20

您没有指定使用哪个测试框架。所以我想提一下 Gallio/MbUnit 测试框架为这一点提供了方便的断言目的:

Assert.IsInstanceOfType<bool>(myValue);

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:

Assert.IsInstanceOfType<bool>(myValue);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文