6
\$\begingroup\$

Background:

Didn't what to have to reference bulky 3rd party lib for inline data driven tests and wanted to use standard MS testing framework.

Created helper InlineDataDrivenTest to provide a workaround for this limitation.

Usage

[TestClass]
public class DataDrivenTests : MiscUnitTests {

    [TestMethod]
    public void Should_Do_Data_Driven_Test() {
        //Arrange 
        var source = new TestDataSource();
        var test = InlineDataDrivenTest.Create(source);
        test.Setup(c => c.TestAdd(0, 0, 0));
        //Act
        test.Run();
        //Assert
        var summary = test.GetResult();
        Assert.IsTrue(summary.Succeeded, summary.Message);
    }

    [TestMethod]
    public void Should_Do_Data_Driven_Test_And_Fail() {
        //Arrange 
        var target = new TestDataSource();
        var test = InlineDataDrivenTest
            .Create(target)
            .Setup(m => m.TestSubtract(0, 0, 0));
        //Act
        test.Run();
        //Assert
        var summary = test.GetResult();
        Assert.IsTrue(summary.Failed == 1, summary.Message);
    }


    public class TestDataSource {

        [DataDrivenTestMethod]
        [DataRow(1, 2, 3)]
        [DataRow(4, 5, 9)]
        public void TestAdd(int a, int b, int expected) {
            Calculator c = new Calculator();
            int actual = c.Add(a, b);
            Assert.AreEqual(expected, actual);
        }

        [DataDrivenTestMethod]
        [DataRow(4, 2, 2)]
        [DataRow(4, 1, 1, DisplayName = "Should fail for demo purposes")]
        public void TestSubtract(int a, int b, int expected) {
            Calculator c = new Calculator();
            int actual = c.Subtract(a, b);
            Assert.AreEqual(expected, actual);
        }

    }

    public class Calculator {

        public int Add(int a, int b) {
            return a + b;
        }

        public int Subtract(int a, int b) {
            return a - b;
        }
    }
}

Thoughts and feed back on code.

This solves the immediate need but I'm looking to improve on current model.

\$\endgroup\$
3
  • \$\begingroup\$ I'd be interesting in seeing the implementation of your attributes. \$\endgroup\$
    – RubberDuck
    Apr 22, 2016 at 8:03
  • \$\begingroup\$ They are just simple custom classes derived from System.Attribute used to provide metadata. At runtime during testing the target class is inspected using reflection for those attributes then tagged methods are invoked with provided data and results aggregated. \$\endgroup\$
    – Nkosi
    Apr 22, 2016 at 12:17
  • \$\begingroup\$ nice. How can I try this ? \$\endgroup\$
    – Marty
    Jun 13, 2017 at 6:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.