鉴于此测试夹具:
[TestClass]
public class MSTestThreads
{
[TestMethod]
public void Test1()
{
Trace.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
[TestMethod]
public void Test2()
{
Trace.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
}
Run Code Online (Sandbox Code Playgroud)
使用MSTest通过Visual Studio或命令行运行测试会打印两个不同的线程号(但它们仍然按顺序运行).
有没有办法强制MSTest使用单个线程运行它们?
有没有办法可以使用TestContext或基础测试类上的其他方法来处理由MSTest框架处理的异常?
如果在我的一个测试中发生未处理的异常,我想旋转exception.Data字典中的所有项目并将它们显示给测试结果,以帮助我找出测试失败的原因(我们通常会将数据添加到帮助我们在生产环境中调试的异常,所以我想做同样的测试).
注意:我没有测试异常是支持HAPPEN(我有其他测试),我正在测试一个有效的情况,我只需要查看异常数据.
这是我正在谈论的代码示例.
[TestMethod]
public void IsFinanceDeadlineDateValid()
{
var target = new BusinessObject();
SetupBusinessObject(target);
//How can I capture this in the text context so I can display all the data
//in the exception in the test result...
var expected = 100;
try
{
Assert.AreEqual(expected, target.PerformSomeCalculationThatMayDivideByZero());
}
catch (Exception ex)
{
ex.Data.Add("SomethingImportant", "I want to see this in the test result, as its important");
ex.Data.Add("Expected", expected);
throw ex;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道为什么我可能不应该有这样的封装方法存在问题,但我们也有子测试来测试PerformSomeCalculation的所有功能......
但是,如果测试失败,99%的时间,我重新运行它通过,所以没有这些信息我无法调试任何东西.我还想在GLOBAL级别上执行此操作,因此如果任何测试失败,我会在测试结果中获取信息,而不是为每个单独的测试执行此操作.
这是将异常信息放在测试结果中的代码.
public void AddDataFromExceptionToResults(Exception ex)
{
StringBuilder whereAmI …Run Code Online (Sandbox Code Playgroud) [TestInitialize]
public void SetUp()
{
//Do required actions before every test
}
[TestMethod]
public void Test1()
{
//Actual test
Assert.AreEqual(1, 0);
}
[TestCleanup]
public void TearDown()
{
//If TestMethod has failed - Get the exeception thrown by the TestMethod. So based on this I can take some action?
}
Run Code Online (Sandbox Code Playgroud)
我能够从TestContext获得TestMethod Name,Test results.但是我想在TestCleanup中获得TestMethod的堆栈跟踪.
其次,我知道实现这一目标的一种方法是在try/catch块中包装测试方法步骤,并将异常设置为变量或属性,并在拆除时对其进行处理.
但是我不想在try/catch块中包装每个testmethod.还有其他更清洁的方法吗?
因为我是MSTest和编程的新手,所以我会详细解释一些详细的解释或示例.