简体   繁体   English

有没有办法用参数创建nunit安装程序

[英]Is there a way to Create nunit Setup with arguments

Is there a way to add arguments to an nunit setup method like this: public void SetUp(Point p = null) { /*code*/ } . 有没有一种方法可以向nunit设置方法中添加参数,例如: public void SetUp(Point p = null) { /*code*/ }

I tried it and got the following exception SetUp : System.Reflection.TargetParameterCountException : Parameter count mismatch 我尝试了它,并收到以下异常SetUp : System.Reflection.TargetParameterCountException : Parameter count mismatch

I think that your point is to avoid code duplication. 我认为您的意思是避免代码重复。 Try to extract base class with overriten method used in SetUp(). 尝试使用SetUp()中使用的overriten方法提取基类。 All derived class will execute tests from base class, with objects prepared in overriten OnSetUp() 所有派生类都将执行基类中的测试,并在重写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. 使用参数化的TestFixture也可能有用。 Tests in class will be lunched per TestFixture, SetUp method also. 课堂上的测试也将根据TestFixture和SetUp方法进行午餐。 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()
    {
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM