Assert.AreEqual 失败时抛出异常

发布于 2024-12-12 00:36:08 字数 478 浏览 0 评论 0原文

我是单元测试的新手,并且使用 Nunit 我不知道如何传递此异常,但有一个 AssertionUnhandled 异常。

我正在做

Assert.AreEqual(exists, 1 == (int)ExecScalar(string.Format("SELECT COUNT(*)    
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{0}{1}' AND TABLE_SCHEMA ='{2}'", 
            (audit ? DBHelper.AuditTablePrefix : ""), tableName, schema)));

Here contains = true ,在我的例子中, other 为 1==0 ,所以它说 Expected True but false 。

那么我应该做什么,因为我不知道如何才能走得更远。

提前致谢。

I am new to the Unit Testing And using Nunit i dont know how to pass this exception but there is an AssertionUnhandled Exception.

I am doing

Assert.AreEqual(exists, 1 == (int)ExecScalar(string.Format("SELECT COUNT(*)    
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{0}{1}' AND TABLE_SCHEMA ='{2}'", 
            (audit ? DBHelper.AuditTablePrefix : ""), tableName, schema)));

Here exists = true and in my case other comes to 1==0 so it says Expected True but false.

So what should i do because i dont know how can i move further.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

软糯酥胸 2024-12-19 00:36:08

看起来您正在尝试确保特定查询返回 1 作为表计数,
我建议您将如此复杂的查询包装在 Assert.DoesNotThrow() 中,并使用 Assert.AreEqual() 来比较两个值:

int numberOfTables = -1;

Assert.DoesNotThrow(() => numberOfTablesRaw = 
             (int)ExecScalar(string.Format(
             "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{0}{1}' AND TABLE_SCHEMA ='{2}'",  
             (audit ? DBHelper.AuditTablePrefix : ""), 
              tableName, 
              schema)));

Assert.AreEqual(1, numberOfTables); 

Looks like you are trying to ensure that particular query returns 1 as tables count,
I would suggest you to wrap such complex query in Assert.DoesNotThrow() and use Assert.AreEqual() to compare two values:

int numberOfTables = -1;

Assert.DoesNotThrow(() => numberOfTablesRaw = 
             (int)ExecScalar(string.Format(
             "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{0}{1}' AND TABLE_SCHEMA ='{2}'",  
             (audit ? DBHelper.AuditTablePrefix : ""), 
              tableName, 
              schema)));

Assert.AreEqual(1, numberOfTables); 
木格 2024-12-19 00:36:08

如果需要抛出异常(预期情况),您可以使用此代码:

Assert.Throws<ArgumentException>(delegate { throw new ArgumentException() } );

或在您的 [Test] 声明附近添加

[ExpectedException(typeof(ArgumentException))]

if it needs to throw exception (expected situation), you can use this code:

Assert.Throws<ArgumentException>(delegate { throw new ArgumentException() } );

or add

[ExpectedException(typeof(ArgumentException))]

near your [Test] declaration.

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