我开始编写单元测试(MS测试,Resharper作为测试执行者)。当我设置LogicalThreadContext(见下文)时,我的测试用例被“中止”。有人知道为什么吗?这是否与单元测试在另一个线程上有关?我该如何解决?
[TestClass]
public class ContextInfoTest
{
private ILog _log;
[TestInitialize]
public void TestInitialize()
{
// logging configured in assembly.info
_log = LogManager.GetLogger(this.GetType());
}
[TestMethod]
public void FigureOutWhyAborting()
{
string input = "blah";
LogicalThreadContext.Properties["mypropertyname"] = input;
string output = LogicalThreadContext.Properties["mypropertyname"] as string;
Assert.AreEqual(input, output);
}
[TestMethod]
public void ThisWorks()
{
string input = "blah";
CallContext.LogicalSetData("mypropertyname", input);
string output = CallContext.LogicalGetData("mypropertyname") as string;
Assert.AreEqual(input, output);
}
奇怪的是,如果我要调试并逐步执行代码,则会调用并传递Assert.AreEqual,因此在该行代码之后发生了某些事情……这就是为什么我认为它可能需要一些帮助用测试线程做,等等。
谢谢!
更新:所以我在MSTest中运行了该测试,并得到了这个异常(Resharper没有显示)
单元测试适配器抛出异常:成员'log4net.Util.PropertiesDictionary,log4net,版本= 1.2.13.0,区域性=中性,PublicKeyToken = 669e0ddf0bb1aa2a'的类型无法解析。
我在VS2013,.Net 4.5上使用log4net v1.2.13。
此链接似乎暗示这是一个引用的程序集问题,但没有解决方法。任何其他想法都将受到欢迎,GAC的log4net不是一个选择。https://issues.apache.org/jira/browse/LOG4NET-398
我最终这样做是为了使其正常工作:
将其放入TestCleanup()方法:
CallContext.FreeNamedDataSlot("log4net.Util.LogicalThreadContextProperties");
所以,我非常感谢您解决此问题以致电FreeNamedDataSlot。这使我想到了对我有用的答案。不必传递类的完整名称空间,我只需要使用类名称:
这曾在我的数据访问层的深处使用:
MySession session = (MySession)System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("MySession");
[TestCleanup]
public void Cleanup()
{
CallContext.FreeNamedDataSlot("MySession");
}
这对我来说很完美!希望这在使用Visual Studio的测试环境时对其他人有所帮助。
我知道这有点老,但是以下内容对我有用。
尽管我的项目和单元测试都引用了log4net,但未在单元测试中对其进行配置。将ThreadContext帮助器更新为以下选项后,我的测试成功了。如果在单元测试中配置了log4net,但仍然出现此问题,则可以改掉编译符号。
var is_configured = log4net.LogManager.GetRepository().Configured;
var props = is_configured
? (ContextPropertiesBase)LogicalThreadContext.Properties
: (ContextPropertiesBase)ThreadContext.Properties;
props[key] = value;
谢谢大家的提示,我尝试:
[TestCleanup]
public void Cleanup()
{
CallContext.FreeNamedDataSlot("log4net.Util.LogicalThreadContextProperties");
}
并且有效!! >>