30

I started to use MSTest 2 DataRow attributes to check multiple cases in a single test:

[TestMethod]
[DataRow(1, 1, 2)]
[DataRow(1, 2, 3)]
public void AdditionWorks(int op1, int op2, int expectedResult)
{
    Assert.AreEqual(expectedResult, new Sut().Add(op1, op2));
}

It works nicely, both in NCrunch and in CI. Only now I noticed that there is special attribute DataTestMethod that is supposed to mark such tests instead of TestMethod.

Is there a difference? A reason to use one variant in particular?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Lukáš Lánský
  • 4,641
  • 3
  • 32
  • 48

2 Answers2

16

Both attributes work because the same attributes are defined in the same namespace as the previous version of MSTest. This was done for backward compatibility.

Reference :

Taking the MSTest Framework forward with “MSTest V2”

Github: Unit Test Samples

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • 1
    I don't understand the backward compatibility argument: `[DataRow]` is new, so if it didn't work with `[TestMethod]`, nothing would be lost. – Lukáš Lánský Oct 26 '17 at 11:51
  • @LukášLánský, the name space is what was backward compatible. the new framework has `TestMethod` in it as well and also the same namespaces from the previous one. That way when you remove the older test framework, all you have to do is add the new `[DataRow]` and everything else will still work. Also `DataTestMethod` is derived from `TestMethod`. Test engines would recognize the data test because of this. – Nkosi Oct 26 '17 at 11:54
  • Do I understand correctly that `[DataTestMethod]` is the newer, preferred option, and `[TestMethod]` works too, but just for compatibility (or more precisely to ease migration), providing less clarity? I.e. that this answer provides the opposite advice than the second-voted, accepted answer? – Palec Dec 21 '22 at 13:27
16

ShreyasRmsft commented the following on GitHub:

Hi @cactuaroid DataTestMethod is not needed. Go ahead and use TestMethod with DataRows to data drive your tests. For any more doubts follow the official docs at https://github.com/microsoft/testfx-docs

https://github.com/microsoft/testfx/issues/614

https://github.com/microsoft/testfx-docs/issues/64

So, according to Microsoft, it is preferred to use TestMethod over DataTestMethod.

Nathan
  • 789
  • 11
  • 20