DEV Community

Ankur Sheel
Ankur Sheel

Posted on • Originally published at ankursheel.com on

3

How to use ApprovalTests with xUnit's Theory attribute

Problem

In ApprovalTests, the Namer generates a unique name for each approved/received file. This filename takes the format of {ClassName}.{MethodName}.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 the 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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay