Skip to content

wrong value received by test method with ITestDataSource and values of struct with property of nullable primitive type #1022

@hauke-w

Description

@hauke-w

After upgrading the test SDK I am facing a bug in the handling of ITestDataSource implementations.
Please look at the example below. There is a struct type "UnlimitedNatural" that is to be tested. It has one uint? typed property for storing the value. Values of this struct are not currectly passed to the "EqualsTest" method when using an ITestDataSource implementation ("MyTestDataSourceAttribute"). The UnlimitedNatural values received by the test method are always equal to new UnlimitedNatural(null). That means the Value property is always null.

I am using Visual Studio 2022 with .net6 and following package versions:
Microsoft.NET.Test.Sdk v17.0.0,
MSTest.TestFramework 2.2.8 and
MSTest.TestAdapter 2.2.8

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;

namespace TestDataSourceBug;
[TestClass]
public class UnitTest1
{
    [TestMethod]
    [MyTestDataSource]
    public void EqualsTest(UnlimitedNatural testObject, UnlimitedNatural other, bool expected)
    {
        var actual = testObject.Equals(other);
        Assert.AreEqual(expected, actual);
    }

    [AttributeUsage(AttributeTargets.Method)]
    private class MyTestDataSourceAttribute : Attribute, ITestDataSource
    {
        public IEnumerable<object[]> GetData(MethodInfo methodInfo)
        {
            return new object[][]
            {
                new object[] { UnlimitedNatural.Zero, UnlimitedNatural.Infinite, false },
                new object[] { UnlimitedNatural.Zero, UnlimitedNatural.Zero, true }
            };
        }

        public string GetDisplayName(MethodInfo methodInfo, object[] data) => string.Join(", ", data);
    }
}

public struct UnlimitedNatural : IEquatable<UnlimitedNatural>
{
    public UnlimitedNatural(uint? value)
    {
        Value = value;
    }

    public static readonly UnlimitedNatural Infinite = new UnlimitedNatural();
    public static readonly UnlimitedNatural One = new UnlimitedNatural(1);
    public static readonly UnlimitedNatural Zero = new UnlimitedNatural(0);

    public uint? Value { get; }

    public override string ToString() => Value?.ToString() ?? "*";

    public override bool Equals([NotNullWhen(true)] object? obj) => obj is UnlimitedNatural other && Equals(other);

    public bool Equals(UnlimitedNatural other) => Value == other.Value;
}

TestDataSourceBug.zip

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions