Home > front end >  Why Records are not able to pass as TestCase in Nunit
Why Records are not able to pass as TestCase in Nunit

Time:10-23

I have a record with 2 params in it, its a compiler error while trying to pass the record as a TestCase().

    [Test]
    [TestCase( myRecord)] // here it complains 
    public void StartGame_SingleValidGame( MyRecord  myRecord)
    {
        var result = myObject.Foo(myRecord);
        Assert.IsTrue(result);
    }


    [SetUp]
    public void Setup()
    {
        var a = new Rec1("Abce", 0);
        var b = new Rec2("Xyz", 0);
        myRecord = new MyRecord(a, b);
    }

Does NUnit support Records ? or there were some issue while I fill the records in [SetUp] function ?

CodePudding user response:

There's only a handful of types that can be used as arguments to attributes, This isn't a Nunit thing, it's a c# thing.

from Attribute parameter types:

The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:

One of the following types:

  • bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.
  • The type object.
  • The type System.Type.
  • Enum types.
  • Single-dimensional arrays of the above types.
  • A constructor argument or public field that does not have one of these types, shall not be used as a positional or named parameter in an attribute specification.

CodePudding user response:

Attribute parameters must be

  • A constant value
  • A typeof expression
  • A single-dimensional array of the above values

If you want to use your variable in your test case, just use a field.

[TestFixture]
public class MyRecordTest
{
    private MyRecord myRecord

    [Test]
    public void StartGame_SingleValidGame()
    {
        var result = myObject.Foo(myRecord);
        Assert.IsTrue(result);
    }

    [SetUp]
    public void Setup()
    {
        var a = new Rec1("Abce", 0);
        var b = new Rec2("Xyz", 0);
        myRecord = new MyRecord(a, b);
    }
}
  •  Tags:  
  • c#
  • Related