Perazim
Perazim

Reputation: 1549

NUnit 3.X - How to pass dynamic parameters into a TestCase or TestCaseSource?

    CGrunddaten m_grdDaten;

    [SetUp]
    public void Init()
    {
        m_grdDaten = new CGrunddaten();
        m_grdDaten.m_cwdGeoH.m_dW = 325.0;
        m_grdDaten.m_cwd_tl.m_dW = 15;

    }


    [Test]
    public void TestMethod()
    {
        m_grdDaten.RechGrdDaten();
        Assert.That(m_grdDaten.m_cwd_pl.m_dW, Is.EqualTo(93344).Within(.1),"Außenluftdruck");
        Assert.That(m_grdDaten.m_cwd_pl_neb.m_dW, Is.EqualTo(93147.3).Within(.1), "Außenluftdruck Nebenluftberechnung");
        Assert.That(m_grdDaten.m_cwd_pl_pmax.m_dW, Is.EqualTo(92928.2).Within(.1), "Außenluftdruck max. zul. Unterdruck");
        Assert.That(m_grdDaten.m_cwdRho_l.m_dW, Is.EqualTo(1.124).Within(.001), "Dichte Außenluft");
        Assert.That(m_grdDaten.m_cwdRho_l_neb.m_dW, Is.EqualTo(1.184).Within(.001), "Dichte Außenluft Nebenluftberechnung");
        Assert.That(m_grdDaten.m_cwdRho_l_pmax.m_dW, Is.EqualTo(1.249).Within(.001), "Dichte Außenluft max. zul. Unterdruck");
    }

Is there a way to get this in a TestCase or TestCaseSource, so that I have only one Assert-line ? I'm talking about this:

I know that TestCase and TestCaseSource are static.... but is there another way?

Upvotes: 0

Views: 1049

Answers (1)

Charlie
Charlie

Reputation: 13726

The best way to do this test would be using the not-yet-implemented multiple asserts feature, so that all the asserts would run even if some failed.

Since that's not available yet, I can understand your wanting to make this into multiple tests, where each gets reported separately. Using test cases makes this possible, of course, even though this is really logically just one test.

The fact that a test case source method must be static doesn't prevent it from creating an instance of your CGrunddaten class. The tests themselves are all just comparing two doubles for equality and don't need to know anything about that class.

You could write something like this:

private static IEnumerable<TestCaseData> GrundDatenDaten
{
    var gd = new CGrunddaten();
    gd.m_cwdGeoH.m_dW = 325.0;
    gd.m_cwd_tl.m_dW = 15;
    gd.RechGrdDaten();

    yield return new TestCaseData(gd.m_cwd_pl.m_dW, 93344, .1, "Außenluftdruck");
    // und so weiter
}

[TestCaseSource("GrundDatenDaten")]
public void testMethod(object actual, object expected, object tolerance, string label)
{
    Assert.That(actual, Is.EqualTo(expected).Within(tolerance), label);
}

However, I don't like that very much as it hides the true function of the test in the data source. I think your original formulation is the best way to do it for now and leaves you with the ability to include the code in an Assert.Multiple block once that feature is implemented.

Upvotes: 1

Related Questions