Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid data when using struct with DynamicData attribute in MSTest testing?

I use MSTest.Framework/MSTest.TestAdapter 2.2.10.

I'm trying to pass test data to Test_Method by using DynamicData attribute. When MyDateTime is struct and I debug Test_Method, the _date field of testData has wrong date. But, when I change MyDateTime to class, then I get the correct date. What can be the problem? Is there any issue with boxing/unboxing of my MyDateTime?

[TestMethod]
[DynamicData(nameof(DataForTestMethod), DynamicDataSourceType.Property)]
public void Test_Method(MyDateTime testData)
{
}

public struct MyDateTime
{
    private DateTime _date;

    public MyDateTime(DateTime dt)
    {
        _date = dt;
    }
}

public static IEnumerable<object[]> DataForTestMethod
{
    get
    {
        var dt = new DateTime(2022,04,30,21,04,22);
        var myDate = new MyDateTime(dt);
        yield return new object[] { myDate };
    }
}
like image 943
theateist Avatar asked Aug 09 '26 11:08

theateist


1 Answers

After spending some time with a .net decompiler, it seems that a struct should implement ISerializable interface for the MSTest framework to correctly return data through DynamicDataAttribute. The body of ISerializable.GetObjectData can even be empty(!). I cannot find what code is responsible for loading DynamicDataAttribute to explain this, but it seems to work if I just add ISerializable interface.

like image 126
theateist Avatar answered Aug 12 '26 01:08

theateist