Using Moles with DateTime

不羁的心 提交于 2019-12-19 03:31:48

问题


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

I want to mole DateTime.Now.

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 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.

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

Any suggestions ?


回答1:


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))]

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



来源:https://stackoverflow.com/questions/5961982/using-moles-with-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!