NUnit. Passing parameters into teardown method

◇◆丶佛笑我妖孽 提交于 2019-12-04 03:58:33

TearDown and SetUp are executed for each of your tests in test fixture. Consider you have following tests:

[TestCase("Joe", "Smith")]
public void Test1(string firstName, string lastName) { ... }

[Test]
public void Test2() { ... }

[TestCase(10)]
public void Test3(int value) { ... }

What is expected signature of TearDown method?

So, answer is no. NUnit does not provide default way of passing test parameter to TearDown method. And I think it won't. You need to add this functionality manually.

It is possible to reference the parameters to the Test directly from the TestContext in the TearDown function.

Something like this.

[Test]
[TestCase("Fred", "Bloggs")]
[TestCase("Joe", "Smith")]
public void MyUnitTest(string firstName, string lastName)
{
}

[TearDown]
public void TearDown()
{
    string firstName = TestContext.CurrentContext.Test.Arguments[0] as string;
    string lastName = TestContext.CurrentContext.Test.Arguments[1] as string;
}

It should be noted that TestContext.CurrentContext.Test.Arguments is just an object array and would be called for every test in the TestFixture regardless of the individual signatures so we ought to be careful to ensure we deal with all possible values in Arguments[] but it certainly is possible to reference these objects in the TearDown function

Actually, this is possible.

If you reference TestContext.CurrentContext.Test.Name in the TearDown, you can get the full method signature that contains the parameters that were passed into it. You will have to parse it, but it's there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!