unittestthinktimetransactionsexample.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Define the TestContext property
public TestContext TestContext { get; set; }
// Use TestInitialize to run code before running each test
private bool inLoadTest = false;
private bool dontKnow = true;
[TestInitialize()]
public void CheckTestContextType() {
if (dontKnow)
{
// Check if the TestContext type is the one that a loadtest provides
if (TestContext.GetType().ToString().Equals("Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapterContext"))
inLoadTest = true;
else
inLoadTest = false;
dontKnow = false;
TestContext.WriteLine("We have a loadtest TestContext: " + inLoadTest);
}
}
[TestMethod]
public void TestMethod1()
{
// Local ThinkTime Parameter with default value 5 seconds, used if no ThinkTime is set in TestContext
int myThinkTime = 5;
// Get think time from test context if set
if (TestContext.Properties.Contains("ThinkTime"))
{
myThinkTime = int.Parse(TestContext.Properties["ThinkTime"].ToString());
TestContext.WriteLine("Using thinktime " + myThinkTime + " from test context");
}
// Dummy transaction, only use BeginTimer if we are running in a loadtest
TestContext.WriteLine("Starting transaction UnitTestTransaction1");
if (inLoadTest) TestContext.BeginTimer("UnitTestTransaction1");
// Think time
System.Threading.Thread.Sleep(myThinkTime * 1000);
// End transaction, only use EndTimer if we are running in a loadtest
TestContext.WriteLine("Ending transaction UnitTestTransaction1");
if (inLoadTest) TestContext.EndTimer("UnitTestTransaction1");
}