如何参数化TestFixtureSetUp(NUnit)

时间:2015-09-22 08:47:46

标签: unit-testing testing nunit automated-tests

在我的测试中,下一个流程发生:

  1. 我在所有测试运行之前做了一些操作(例如购买产品)
  2. 然后在每次测试中我检查一个断言
  3. 我使用NUnit框架来运行测试,因此我使用[TestFixtureSetUp]来标记在所有测试之前完成一次的一组操作。然后我使用[Test]或[TestCase()]来运行测试。

    通常我需要检查相同的内容但执行不同的流程。所以我必须参数化[TestFixtureSetUp]。我可以以某种方式做到吗?

    所以我希望在所有测试依赖参数之前执行一次执行的操作。

    如果可以使用不同的框架或不同的流程结构,请告诉我)

    我的代码示例:

     [TestFixtureSetUp] //This will be done once before all tests
     public void Buy_Regular_One_Draw_Ticket(WayToPay merchant)
     {
              //here I want to do some actions and use different merchants to pay. 
    
              //So how can I send different parameters to this method?
    
     }
    

1 个答案:

答案 0 :(得分:3)

伙计解决方案是下一个:类的构造函数在[TestFixtureSetUp]之前运行,因此现在在[TestFixtureSetUp]中所做的所有操作都是在类的构造函数中完成的。

我们有能力将参数发送给构造函数!为此,我们使用[TestFixture()]。

整个代码是下一个:

[TestFixture(WaysToPay.Offline)]
[TestFixture(WaysToPay.Neteller)]
public class DepositTests
{
        //Constructor takes parameters from TestFixture
        public DepositTests(WaysToPay merchant) 
        {
            //Do actions before tests considering your parameters
        }

        [Test]
        public void Your_test_method()
        {
            //do your verification here
        }
    }

使用此方法而不是使用[TestFixtureSetUp]可以使您的测试更加灵活。因此行为与[TestFixtureSetUp]可以获取参数的行为相同。