Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you pass data to a test fixture just like you pass data to test cases?

Tags:

nunit

Can you pass data to a NUnit3 test fixture just like you pass data to test cases? Would it even make sense to do this? (run a suite (fixture class) based on a parameter)

like image 419
Saleem Avatar asked Jun 28 '16 14:06

Saleem


1 Answers

Absolutely!

If there's a limited amount of parameters you need to pass in, you can just put these in the normal [TestFixture] attribute, and they will be passed to the constructor of the TestFixture. e.g.

[TestFixture("hello", "hello", "goodbye")]
[TestFixture("zip", "zip", "zap")]
public class ParameterizedTestFixture
{
    private string eq1;
    private string eq2;
    private string neq;

    public ParameterizedTestFixture(string eq1, string eq2, string neq)
    {
        this.eq1 = eq1;
        this.eq2 = eq2;
        this.neq = neq;
    }

This version would run the test fixture twice, with the two different sets of parameters. (Docs)

If you have more parameters, you may wish to look at [TestFixtureSource] - which works much the same way, but allows you to calculate your parameters in a static method, as opposed to explicity specified in an attribute. (Docs) Something such as this:

[TestFixtureSource(typeof(FixtureArgs))]
public class MyTestClass
{
    public MyTestClass(string word, int num) { ... }

    ...
}

class FixtureArgs: IEnumerable
{
    public IEnumerator GetEnumerator()
    {
        yield return new object[] { "Question", 1 };
        yield return new object[] { "Answer", 42 };
    }
}

Finally, if you need to pass parameters in at run-time, this is also possible through the --params command line option, new in NUnit v3.4. It doesn't look like this is documented yet, but you can pass it into the NUnit console command line in the format --params:X=5;Y=7". It can then be retrieved through the TestContext.Parameters class.

like image 81
Chris Avatar answered Oct 22 '22 18:10

Chris