Search code examples
c#mstest

MSTest - DataTestMethod throws exception System.ArgumentException: Object of type 'System.Decimal' cannot be converted to type 'System.Double'


I have a simple parameterized unit test in a .NET Core 3.1 test project (using MSTest) which runs successfully. It looks something like this:

[DataRow(0.5)]
[DataRow(-1.5)]
[DataTestMethod]
public void MyParameterizedTest(double value)
{
   ...
}

However after updating the project to .NET 5, the test failed, and threw the following exception:

System.ArgumentException: Object of type 'System.Decimal' cannot be converted to type 'System.Double'.
  Stack Trace:
      at System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast)
   at System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)

I tried casting the value, and also tried using [DynamicData] but the same exception occurred.

As a last a resort, I changed the test to convert a string value back to a double. It works, but it feels "hacky".

[DataRow("0.5")]
[DataRow("-1.5")]
[DataTestMethod]
public void MyParameterizedTest(string stringValue)
{
   var doubleValue = Convert.ToDouble(stringValue);
   ...
}

Any other suggestions how I can resolve this issue?


Solution

  • Updating the related MSTest NuGet packages resolved this issue, and I was able to get my original parameterized test using doubles to work.

    The NuGet packages I updated were:

    • Microsoft.NET.Test.Sdk (16.10.0 from 16.5.0)
    • MSTest.TestAdapter (2.2.5 from 2.1.0)
    • MSTest.TestFramework (2.2.5 from 2.1.0)