正在从当前正在运行的单元测试中获取信息
本文关键字:信息 单元测试 获取 运行 | 更新日期: 2023-09-27 18:28:44
我必须从助手类的静态方法中找到有关当前运行的UnitTest的信息。创意是从每次测试中获得一把独特的钥匙。
我考虑过使用TestContext
,不确定它是否可行。
示例
[TestClass]
public void MyTestClass
{
public TestContext TestContext { get; set; }
[TestMethod]
public void MyTestMethod()
{
TestContext.Properties.Add("MyKey", Guid.NewGuid());
//Continue....
}
}
public static class Foo
{
public static Something GetSomething()
{
//Get the guid from test context.
//Return something base on this key
}
}
我们目前正在使用Thread.SetData
将此密钥存储在线程上,但如果测试的代码生成多个线程,则会产生问题。对于每个线程,我需要为给定的单元测试获得相同的密钥。
Foo.GetSomething()
不是从单元测试本身调用的。调用它的代码是Unity注入的模拟代码。
编辑
我将稍微解释一下上下文,因为它似乎令人困惑。
通过统一创建的对象是实体框架的上下文。当运行单元测试时,上下文在Foo.GetSomething
创建的结构中获取数据。让我们称之为DataPersistance
。
DataPersistance
不能是单例,因为单元测试会相互影响。
我们目前每个线程有一个DataPersistance
的实例,只要测试的代码是单线程的,它就很好。
我想要每个单元测试一个DataPersistance
的实例。如果每个测试都能得到一个唯一的guid,我就可以解析这个测试的实例。
public static class Foo
{
public static Something GetSomething(Guid guid)
{
//Return something base on this key
return new Something();
}
}
测试:
[TestClass]
public void MyTestClass
{
public TestContext TestContext { get; set; }
[TestMethod]
public void MyTestMethod()
{
Guid guid = ...;
Something something = Foo.GetSomething(guid);
}
}