在我的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?
答案 0 :(得分:4)
您可以通过LoadTest Plugin并使用UserContext
来完成此操作。每个虚拟用户都有自己的UserContext
,您可以使用它来传递/检索TestContext
中的数据。
在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
}
使用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);
}
要访问测试中的UserContext
,请在每个UnitTest上添加以下属性:
public LoadTestUserContext UserContext
{
get
{
return TestContext.Properties["$LoadTestUserContext"] as LoadTestUserContext;
}
}
Test Mix Model = Based on sequential order
时,您的测试将按照您在Test Mix
上添加的顺序执行。 注意:为此,您必须在单个UnitTest文件中添加每个TestMethod
。如果您将它们放在同一个文件中,则TestInialize
和TestCleanup
方法将在包含的每个TestMethod
上执行,并且您可能会尝试访问您没有的数据(例如试图在CreateOrder上获取orderNumber)。