在 NUnit 测试期间的拆卸事件中,如何获取应用于刚刚测试的方法的属性?
我有一个正在运行的测试方法。 当该方法生成异常时,我想知道测试的名称是什么以及异常内容。
在测试的拆解中,我想访问此信息。 我如何从 [TearDown]
属性方法访问它?
I have a test method that is run. When the method generates an exception I want to know what the name of the test was and the exception content.
In the teardown for the test I want to get access to this information. How would I get access to it from the [TearDown]
attributed method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在测试拆卸方法中访问文本上下文对象
我不知道哪个版本首先支持它,但我的是24。
You can access text context objects in test tear down method
I don't know which version was first to support it, but mine is 24.
我认为 nunit 中没有内置的好方法,但这并不是一个很难解决的问题。 只需将测试包装在 try/catch 块中,捕获任何异常,并将它们(和测试名称)保存到测试类中的私有成员变量中。 然后您就可以通过 TearDown 方法进行访问。
不是特别优雅,但很有效。
I don't think there's a good way built in to nunit, but it's not a hard problem to resolve. Just wrap your tests in a try/catch block, catch any exceptions, and save them (and the test name) to a private member variable in your test class. Then you've got access from your TearDown method.
Not particularly elegant, but it works.
另一种解决方案是使用模板方法并使用此方法运行所有测试。 例如:
当您的测试使用一些必须在测试前初始化并在测试后释放的资源(例如临时文件)时,此模式特别有用。 在这种情况下,您可以在测试委托中使用类型参数。
另一个优点是你可以轻松地让测试在不同的线程上运行,使用不同的文化等。
缺点很明显:它迫使你在每个测试中使用 lambda 方法。
Another solution would be to use a template method and run all tests using this method. For example:
This pattern is particularly useful when your test uses some resources that must be initialized before test and disposed after test (e.g. temporary file). In that case, you can use a type parameter in test delegate.
Another advantage is that you can easily let the test run on different thread, using different culture etc.
Disadvantage is clear: it forces you to use lambda method in every test.
选项 1:我认为您不能。 或者更确切地说,我不知道你可以。 我解决此需求的方法是在特定测试中使用 try/catch,对异常执行我想要的操作,然后在 catch 块中再次抛出,以便测试可能失败。
选项 2:如果您还没有走得太远,您可能需要使用 xUnit,它具有不同的异常期望模型,并且可能提供您正在寻找的一些控制。
OPTION 1: I don't think you can. Or rather, I don't know that you can. How I approach this need is to use a try/catch on the specific tests, do what I want with the exception and then throw again within the catch block so that the test could fail.
OPTION 2: If you've not gone too far along, you may want to use xUnit which has a different exception expectation model and may provide some of the control you are looking for.