Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to Create nunit Setup with arguments

Tags:

c#

nunit

Is there a way to add arguments to an nunit setup method like this: public void SetUp(Point p = null) { /*code*/ }.

I tried it and got the following exception SetUp : System.Reflection.TargetParameterCountException : Parameter count mismatch

like image 518
jgerstle Avatar asked Feb 22 '13 17:02

jgerstle


1 Answers

I think that your point is to avoid code duplication. Try to extract base class with overriten method used in SetUp(). All derived class will execute tests from base class, with objects prepared in overriten OnSetUp()

[TestFixture]
public class BaseTestsClass
{
    //some public/protected fields to be set in SetUp and OnSetUp

    [SetUp]
    public void SetUp()
    {
        //basic SetUp method
        OnSetUp();
    }

    public virtual void OnSetUp()
    {
    }

    [Test]
    public void SomeTestCase()
    {
        //...
    }

    [Test]
    public void SomeOtherTestCase()
    {
        //...
    }
}

[TestFixture]
public class TestClassWithSpecificSetUp : BaseTestsClass
{
    public virtual void OnSetUp()
    {
        //setup some fields
    }
}

[TestFixture]
public class OtherTestClassWithSpecificSetUp : BaseTestsClass
{
    public virtual void OnSetUp()
    {
        //setup some fields
    }
}

Using parametrised TestFixture also can be usefull. Tests in class will be lunched per TestFixture, SetUp method also. But remember that

Parameterized fixtures are (as you have discovered) limited by the fact that you can only use arguments that are permitted in attributes

Usage:

[TestFixture("some param", 123)]
[TestFixture("another param", 456)]
public class SomeTestsClass
{
    private readonly string _firstParam;
    private readonly int _secondParam;

    public WhenNoFunctionCodeExpected(string firstParam, int secondParam)
    {
        _firstParam = firstParam;
        _secondParam = secondParam;
    }

    [Test]
    public void SomeTestCase()
    {
        ...
    }
}
like image 93
michalczukm Avatar answered Oct 19 '22 23:10

michalczukm