如何将数据从UnitTest传递到LoadTest?

时间:2013-06-03 15:53:57

标签: c# unit-testing load-testing test-framework

在我的UnitTest中,我正在创建需要在将来的UnitTests中引用的数据。例如:

[TestMethod]
public void CreateOrder()
{
    Order order = new Order();
    int orderNumber = order.Create();
    // return orderNumber;
}

[TestMethod]
public void ProcessOrder()
{
    int orderNumber = (int)TestContext.Properties["OrderNumber"];
    ProcessOrder(orderNumber);
}

我需要保存'orderNumber',以便另一个UnitTest(可能在另一个代理上)可以使用此生成的订单。我已经决定我可以使用数据库了,但是我必须像删除项目中的队列那样操作它,并且不想去那条路。

有没有办法将orderNumber'返回'到LoadTest并将其作为Context参数传递给另一个UnitTest?

1 个答案:

答案 0 :(得分:4)

您可以通过LoadTest Plugin并使用UserContext来完成此操作。每个虚拟用户都有自己的UserContext,您可以使用它来传递/检索TestContext中的数据。

  1. Create a load test plugin
  2. TestStarting&上添加事件处理程序TestFinished个事件。 TestStarting方法会在TestInitialize方法之前触发,而TestFinished会在TestCleanup之后触发:

    public void TestStarting(object sender, TestStartingEventArgs e)
    {
        // Pass the UserContext into the TestContext before the test started with all its data retrieved so far data.
        // At the first test it will just be empty
        e.TestContextProperties.Add("UserContext", e.UserContext);
    }
    
    public void TestFinished(object sender, TestFinishedEventArgs e)
    {
        // do something with the data retrieved form the test 
    }
    
  3. 使用TestInitialize& TestCleanup从/ UserContext获取/添加数据:

    [TestInitialize]
    public void TestInitialize()
    {
        // Get the order number which was added by the TestCleanup method of the previous test
        int orderNumber = (int) UserContext["orderNumber"];
    }
    
    [TestCleanup]
    public void TestCleanup()
    {
        // When the CreateOrder test is completed, add the order number to the UserContext
        // so the next will have access to it
        UserContext.Add("orderNumber", orderNumber);
    }
    
  4. 要访问测试中的UserContext,请在每个UnitTest上添加以下属性:

    public LoadTestUserContext UserContext
    {
        get
        {
            return TestContext.Properties["$LoadTestUserContext"] as LoadTestUserContext;
        }
    }
    
  5. 在您加载测试配置集Test Mix Model = Based on sequential order时,您的测试将按照您在Test Mix上添加的顺序执行。
  6. 注意:为此,您必须在单个UnitTest文件中添加每个TestMethod。如果您将它们放在同一个文件中,则TestInializeTestCleanup方法将在包含的每个TestMethod上执行,并且您可能会尝试访问您没有的数据(例如试图在CreateOrder上获取orderNumber)。