ApprovalTests with TestCase (Nunit) use the same approval file

1k Views Asked by At

I have a problem that using ApprovalTests.Net and NUnit all the tests that are run use the same approval file which name originates from Test method name.

Is it possible to specify somehow for each test case separate approval file?

[Test]
[TestCase("test",TestName="Test1")]
[TestCase("test2",TestName="Test2")]
Testing_Method(string param)
{
   //somestuff
   ObjectApprover.VerifyJson(someObject); // fails for second case 
                                          // because it uses the same 
                                          // approval file as the first case,
                                          // which is not the same
}
2

There are 2 best solutions below

0
llewellyn falco On BEST ANSWER

You need to use

ApprovalResults.ForScenario("extra info")

Like such:

[Test]
[TestCase("test",TestName="Test1")]
[TestCase("test2",TestName="Test2")]
Testing_Method(string param)
{
   //somestuff
   using (ApprovalTests.Namers.ApprovalResults.ForScenario(param))
   {
       ObjectApprover.VerifyJson(someObject); 
   }
}

This will result in 2 approval files:

TestClassName.Testing_Method.ForScenario.Test1.approved.json
TestClassName.Testing_Method.ForScenario.Test2.approved.json
1
VitaliiP On

Instead of [TestCase] attribute, you could use [TestCaseSource] attribute.

https://ignas.me/tech/nunit-testcasesource-example/ - TestCaseSource example with explanation.