Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't xUnit.net's FactAttribute AttributeUsage.Inheritable?

Having not written a unit testing framework before, it seems to me that an inheritable Fact attribute would make it easier to write abstract test classes or test interfaces if certain types in an assembly all needed to be tested for similar things.

Is there a design reason that Fact isn't inheritable? I think other test frameworks (NUnit, MSTest, MbUnit, etc) that use attributes to identify test methods are similarly designed. What am I missing?

Here's the start of what the FactAttribute for xunit (version 1.9.1.1600) looks like:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class FactAttribute : Attribute
{

I'm trying to understand why it doesn't look like the following instead:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class FactAttribute : Attribute
{ 
like image 932
Scott Lawrence Avatar asked Jul 18 '12 16:07

Scott Lawrence


3 Answers

The FactAttribute is inheritable.

Have a look at this article: http://iridescence.no/post/Extending-xUnit-with-a-Custom-ObservationAttribute-for-BDD-Style-Testing.aspx

I think it is really useful sometimes.

like image 151
RegiS Avatar answered Nov 02 '22 02:11

RegiS


I often use the template pattern in my tests (which seems to be what you are trying to accomplish), and it works just fine with xUnit.net.

public abstract class TestBase
{
    [Fact]
    public void Verify()
    {
        // Step 1
        // Step 2

        // Overridable step 3
        DoStuff();

        // Assert
    }

    protected abstract void DoStuff();
}

public class Test1 : TestBase
{
    protected override void DoStuff()
    {
        // Test1 variation
    }
}

public class Test2 : TestBase
{
    protected override void DoStuff()
    {
        // Test2 variation
    }
}

Verify is executed twice -- once on an instance Test1 and again on an instance of Test2.

Hope this helps.

like image 32
bricelam Avatar answered Nov 02 '22 03:11

bricelam


I never heard of an Attribute being inheritable, as it is with classes. You should have no problem though writing a base class with the common test methods and applying the [Fact] attribute to methods in the derived class.

like image 1
Otávio Décio Avatar answered Nov 02 '22 04:11

Otávio Décio