Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# NUnit TestCaseSource Passing Parameter

Tags:

c#

nunit

I have the following method which generates a set of test cases!

public IEnumerable<ResultsOfCallMyMethod> PrepareTestCases(param1)
{
    foreach (string entry in entries)
    {
        yield return callMyMethod(param1);
    }
}

How can I pass param which is of type string as a parameter to my PrepareTestCases() method?

Is there a way to do the following:

[Test, Category("Integration"), TestCaseSource("PrepareTestCases", param1)]
public void TestRun(ResultsOfCallMyMethod testData)
{
    // do something!
}
like image 822
joesan Avatar asked Feb 19 '15 10:02

joesan


2 Answers

I've made a change for this in the latest version of nunit which is about to be released (3.2).

https://github.com/nunit/nunit/blob/4f54fd7e86f659682e7a538dfe5abee0c33aa8b4/CHANGES.txt

  • TestCaseSourceAttribute now optionally takes an array of parameters that can be passed to the source method

It is now possible to do something like this

[Test, Category("Integration"), TestCaseSource(typeof(MyDataSources),"PrepareTestCases", new object[] {param1})]
public void TestRun(ResultsOfCallMyMethod testData)
{
// do something!
}

private class MyDataSources
{
  public IEnumerable<ResultsOfCallMyMethod> PrepareTestCases(param1)
  {
    foreach (string entry in entries)
    {
        yield return callMyMethod(param1);
    }
  }
}
like image 92
Joe Avatar answered Oct 05 '22 21:10

Joe


If you look at TestCaseSourceAttribute doc you will see there is no any way to pass the parameter to the method which returns test cases.

The method, which generates test cases, should be parameterless.

So, assuming you are going to avoid code duplication and you need to reuse the same method to generate a few test case lists, I'd recommend you to do the following:

  1. Write parameterized method which actually generates test cases sets:
    (PrepareTestCases() already does that)

    public IEnumerable<ResultsOfCallMyMethod> PrepareTestCases(string param)
    {
        foreach (string entry in entries)
        {
            yield return CallMyMethod(param);
        }
    }
    
  2. Write parameterless wrappers which call test cases generator and pass desired parameter there:

    public IEnumerable<ResultsOfCallMyMethod> PrepareTestCases_Param1()
    {
        return PrepareTestCases("param1");
    }
    
    public IEnumerable<ResultsOfCallMyMethod> PrepareTestCases_Param2()
    {
        return PrepareTestCases("param2");
    }
    
  3. Write test methods and pass paremeterless wrappers there as test case sources:

    [TestCaseSource("PrepareTestCases_Param1")]
    public void TestRun1(ResultsOfCallMyMethod data)
    {
    }
    
    [TestCaseSource("PrepareTestCases_Param2")]
    public void TestRun2(ResultsOfCallMyMethod data)
    {
    }
    
like image 11
Alexander Stepaniuk Avatar answered Oct 05 '22 21:10

Alexander Stepaniuk