Search code examples
c#unit-testingmstestvisual-studio-2017

Using decimal values in DataRowAttribute


I've got a c# assembly for Tests to run in Visual Studio 2017 using MSTest.TestAdaptor 1.1.17. I want to use a DataTestMethod to run a test with several datasets. My Problem is, I want to use decimal values in my DataRows but can't:

[DataTestMethod]
[DataRow(1m, 2m, 3m)]
[DataRow(1, 2, 3)]
[DataRow(1.0, 2.0, 3.0)]
public void CheckIt(decimal num1, decimal num2, decimal expected)
{
}

When I try to use [DataRow(100m, 7m, 7m)] it won't even compile the source: error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type..

When I use [DataRow(100, 7, 7)] the test will fail since my test expects decimal but gets int32 as value.

When I use [DataRow(100.0, 7.0, 7.0)] the test will fail since my test expects decimal but gets double as value.

Why can't I use decimal numbers in a DataRow?


Solution

  • It's because decimal is not a primitive type

    The solution is to use strings and then convert your parameters in your test.

    Update from comments: Doubles are simpler for cast (decimal)doubleTotal instead of string conversions