NUnit. Passing parameters into teardown method
Asked Answered
M

3

10

I'm using NUnit. I have my test method defined likeso:

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

After a TestCase has finished, it goes into the TearDown Method. What'd like to do, is have those TestCase parameters that are passed into the test method but also passed into the TearDown method.

Something like this:

[TearDown]
public void TearDown(string firstName, string lastName)
{
  ...
}

I'm hoping that NUnit supports this out-of-the-box. Otherwise, I need to write bespoke code in the test method to store the test data in a collection. Then that collection is used in the TearDown method.

If anyone has any thoughts .. would be great! Thanks. Christian

Mencius answered 24/4, 2012 at 9:17 Comment(0)
M
10

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

Mummer answered 21/12, 2017 at 20:10 Comment(1)
+1. Note: if someone is going to use the answer approach, the version of NUnit should be checked - array of Arguments is available since v3.7,Irisirisa
M
8

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.

Malodorous answered 24/4, 2012 at 11:54 Comment(1)
I thought that NUnit didn't support it after much Googling. But thanks for your answer. Always good to check.Mencius
C
5

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.

Creepie answered 18/3, 2015 at 23:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.