Published on
Last Updated on
Estimated Reading Time: 1 min
Problem
In ApprovalTests, the Namer generates a unique name for each approved/received file. This filename takes the format of ..approved.txt.
This works perfectly for Fact based tests. But, if you are writing a Theory based test, the filename will not be unique as a theory-based test is data-driven and therefore has multiple calls to the same method.
Example
Let's look at an example.
public class TestClass
{
[InlineData(true)]
[InlineData(false)]
[Theory]
public void Test(bool flag)
{
var result = TestThisMethod(flag);
Approvals.Verify(result);
}
}
In the above snippet, the filename generated for both the tests will be TestClass.Test.approved.txt. This means that you have only 1 approval file for both tests.
Solution
The naming pattern of the default namer is [ClassName].[MethodName].[AdditionalInformation(optional)].approved.[Extension]. So, we can leverage the AdditionalInformation part to generate unique filenames for our tests.
public class TestClass
{
[InlineData(true)]
[InlineData(false)]
[Theory]
public void Test(bool flag)
{
NamerFactory.AdditionalInformation = $"Flag-{flag}";
var result = TestThisMethod(flag);
Approvals.Verify(result);
}
}
Now, when we run the tests, 2 files will be generated.
- TestClass.Test.Flag-true.approved.txt
- TestClass.Test.Flag-false.approved.txt
Note: We can pass any information to the AdditionalInformation property as long as it is unique between tests.