Tho*_*del 6 unit-testing moles microsoft-fakes
我最近和Moles一起工作,现在我转向Fakes.在我的旧测试项目中,我有一个测试设置,看起来像这样:
[TestInitialize]
public void Setup()
{
//...
}
Run Code Online (Sandbox Code Playgroud)
在那里,我做了一些必要的设置就像设置我的一些鼹鼠对象.
鼹鼠的测试方法看起来有点像(还有[HostType("Moles")]指定它使用moles对象.
[TestMethod]
[HostType("Moles")]
public void MolesTestMethod()
{
//...
}
Run Code Online (Sandbox Code Playgroud)
现在,在Fakes中,他们不再使用HostType属性了.相反,他们使用ShimsContext,您可以在其中使用"模拟"类.它看起来像这样:
[TestMethod]
public void FakesTestMethod()
{
using (ShimsContext.Create())
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
如果您不使用此上下文,则最终可能会显示错误消息.它基本上说FakesTestMethod中有一个ShimInvalidOperationException,你必须按照下面描述的方式使用ShimsContext.Create())
-- C#:
using Microsoft.QualityTools.Testing.Fakes;
using(ShimsContext.Create())
{
// your test code using Shims here
}
-- VisualBasic.NET
Imports Microsoft.QualityTools.Testing.Fakes
Using ShimsContext.Create
' your test code using Shims here
End Using
Run Code Online (Sandbox Code Playgroud)
所以我试着把我的设置调用放到那个上下文中,结果是这样的:
[TestInitialize]
public void Setup()
{
using(ShimsContext.Create())
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我在我的Setup方法中使用这个上下文,那里完成的所有设置都会在之后的上下文中运行,并且当单元测试实际上即将运行时将不再有效,这实际上不是我想要的测试设置方法.
我通过在测试方法本身内部使用use来解决这个问题,并且只是在这个上下文中和测试代码之前调用私有安装方法.此设置方法现在执行所有处理,在[TestInitialize]设置方法之前执行.代码看起来像这样:
[TestMethod]
public void PerformActionFromConfigActionStateActionIdIsSet()
{
using (ShimsContext.Create())
{
Setup();
//...
}
}
Run Code Online (Sandbox Code Playgroud)
我现在的问题是,这个解决方案完全"杀死"了[TestInitialize]设置方法的想法.我必须将此代码复制到EACH测试方法和最重要的部分:在这个Setup()方法中创建的对象将被创建并销毁用于EACH测试,这根本不是理想的!
有没有其他方法在Fakes中设置测试数据?任何帮助表示赞赏!
Dre*_*sel 12
定义一个范围,在该范围之外将放置一个或多个对象.
您可以通过调用ShimsContext.Create()
并使用using块将其包装来创建IDisposable实例.在初始化Fakes类并离开使用范围后,您的配置将被处理掉.
我建议创建IDisposable实例并在测试结束时手动调用Dispose.
如果你想避免为每个测试创建Context,我还建议使用ClassInitialize和ClassCleanup而不是TestInitialize和TestCleanup,因为它应该足以初始化Shims一次用于alle测试.只有在没有其他依赖项时才可以这样做(参见Oleg Sych的回答).
[TestClass]
public class TestClass1
{
protected static IDisposable Context { get; set; }
[ClassInitialize]
public static void ClassInitialize(TestContext testContext)
{
// Create ShimsContext
Context = ShimsContext.Create();
// TODO: Additional setup
}
[ClassCleanup]
public static void ClassCleanup()
{
Context.Dispose();
Context = null;
}
[TestMethod]
public void TestMethod1()
{
// Fakes should be initialized correctly here
}
[TestMethod]
public void TestMethod2()
{
// Fakes should be initialized correctly here
}
}
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.