将Moles与DateTime一起使用 [英] Using Moles with DateTime

查看:110
本文介绍了将Moles与DateTime一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始在单元测试中使用Moles,并且在文档方面有些挣扎.

I'm starting to using Moles in unit tests and am struggling a little with documentation.

我要调教DateTime.现在.

I want to mole DateTime.Now.

如果您环顾旧的方法是添加对mscorlib的引用,然后为其添加一个stubx文件(添加新项->用于测试的存根和摩尔).

If you look around the old way of doing this was to add a reference to mscorlib, then add a stubx file for it (Add New Item -> Stubs And Moles For Testing).

测试用存根和痣"模板已被弃用,而您所需要做的就是右键单击参考并选择添加痣装配".

The 'Stubs and Moles for Testing' template has been deprecated, instead all you need do is to right click a reference and select 'Add moles assembly', whch is fine.

VS2010不允许您直接添加对mscorlib的引用,因为我们有对"System"的引用,这是可以的,因为我可以在对象浏览器中看到DateTime作为此命名空间的一部分.

VS2010 does not allow you to add a reference directly to mscorlib, because we have a reference to "System", this is ok as I can see DateTime in object browser as part of this namespace.

如果我为系统参考添加痣组件并进行重建,我仍然无法解析MDateTime.

If I add a moles assembly for the System reference and rebuild I still can't resolve an MDateTime.

有什么建议吗?

推荐答案

对于mscorlib的Moles,您需要直接在测试项目的引用"上单击鼠标右键.您将为mscorlib添加Moles程序集. 然后,将using System.Moles;添加到测试类中,因为您需要Moles of System.DateTime(实际上,您需要更多).

For Moles of mscorlib, you need to right-click directly on the References of your test project. You will have Add Moles Assembly for mscorlib. Then, add using System.Moles;to your test class because you want Moles of System.DateTime (actually, you need a little more).

[TestMethod()]
[HostType("Moles")]
public void DateTimeMolesTest()
{
    DateTime date = new System.DateTime(2000, 1, 1, 2, 3, 4, 5);
    MDateTime.NowGet = () => date;
    Assert.AreEqual(date, DateTime.Now);
}

如果运行此测试,它将失败,因为您需要添加:

If you run this test, it will fail because you need to add:

using Microsoft.Moles.Framework;
[assembly: MoledType(typeof(System.DateTime))]

然后,您的测试将成功. 别忘了Moles不能与某些特殊类型的mscorlib一起使用.

Then, your test will succeed. Don't forget that Moles cannot be used with some special types of mscorlib.

这篇关于将Moles与DateTime一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆