本文介绍了NUnit的预期异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 限时删除!! 我已经有了一套测试案例,其中一些预计将抛出异常。正因为如此,我已经为这些测试的属性期望像这样的例外:I've got a set of test cases, some of which are expected to throw exceptions. Because of this, I have have set the attributes for these tests to expect exceptions like so:[ExpectedException("System.NullReferenceException")]当我运行我的测试,在当地一切都很好。然而,当我将我的测试,在运行的TeamCity CI服务器,我所有的测试,所预期的异常失败。这是一个已知的bug。When I run my tests locally all is good. However when I move my tests over to the CI server running TeamCity, all my tests that have expected exceptions fail. This is a known bug.据我所知,也有个 Assert.Throws<> 和 Assert.Throws 方法。I am aware that there is also the Assert.Throws<> and Assert.Throws methods that NUnit offers.我的问题是我怎么能利用这些,而不是我目前使用属性?My question is how can I make use of these instead of the attribute I'm currently using?我已经有大约计算器一看,并试图几件事没有这似乎为我工作。I've had a look around StackOverflow and tried a few things none of which seem to work for me.有一个简单的1号线的解决方案使用此?Is there a simple 1 line solution to using this?推荐答案我不知道你试过那是什么给你的麻烦,但你可以在一个lambda简单地传递作为第一个参数Assert.Throws。这里有一个从我的测试之一传递:I'm not sure what you've tried that is giving you trouble, but you can simply pass in a lambda as the first argument to Assert.Throws. Here's one from one of my tests that passes:Assert.Throws<ArgumentException>(() => pointStore.Store(new[] { firstPoint })); 好吧,这个例子可能是一个有点冗长。假设我有一个测试Okay, that example may have been a little verbose. Suppose I had a test[Test][ExpectedException("System.NullReferenceException")]public void TestFoo(){ MyObject o = null; o.Foo();} 这通常会通过,因为 o.Foo() 将提高一个空引用异常。which would pass normally because o.Foo() would raise a null reference exception.您然后将放弃的ExpectedException 属性,换你到 o.Foo调用()在 Assert.Throws 。You then would drop the ExpectedException attribute and wrap your call to o.Foo() in an Assert.Throws.[Test]public void TestFoo(){ MyObject o = null; Assert.Throws<NullReferenceException>(() => o.Foo());}的 Assert.Throws 试图调用的代码片段,表示为代表,以验证它抛出一个特定的异常。在()=> DoSomething的()语法代表的的λ的,基本上是一个匿名方法。所以在这种情况下,我们告诉 Assert.Throws 来执行该段 o.Foo()。Assert.Throws "attempts to invoke a code snippet, represented as a delegate, in order to verify that it throws a particular exception." The () => DoSomething() syntax represents a lambda, essentially an anonymous method. So in this case, we are telling Assert.Throws to execute the snippet o.Foo().所以,不,你不只是添加一行像你这样一个属性;你需要明确包测试的部分,将抛出异常,在调用 Assert.Throws 。你不这样做的不一定的有使用lambda,但是这往往是最方便的。So no, you don't just add a single line like you do an attribute; you need to explicitly wrap the section of your test that will throw the exception, in a call to Assert.Throws. You don't necessarily have to use a lambda, but that's often the most convenient. 这篇关于NUnit的预期异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-09 00:56