Today I needed to unit test a component which uses System.DateTime.Now (C# .NET) ...
The good answer:this actually works using System.Fakes (sorry, no idea in which edition, but in ultimate it works perfectly). In the past microsoft seemed to use "moles" (see: http://research.microsoft.com/en-us/projects/moles/ ) instead of "fakes".
Using fakes:
Code:
Kind regards, Daniel
The good answer:this actually works using System.Fakes (sorry, no idea in which edition, but in ultimate it works perfectly). In the past microsoft seemed to use "moles" (see: http://research.microsoft.com/en-us/projects/moles/ ) instead of "fakes".
Using fakes:
- Create a Unit-Test Project
- Select References
- Right-Click on "add fakes assembly"
- this adds ref to "...Fakes.dll"
- Fakes Folder with xml stuff
- now you enabled fakes for system (most of the time mscorlib will be faked too by VS)...
- start to use it
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 | [TestMethod] public void CheckCurrentDate_ResultFixed2012() { // Arrange using (ShimsContext.Create()) { // Act System.Fakes.ShimDateTime.NowGet = () => new DateTime(2012, 12, 31); // Assert Assert.AreEqual(2012, DateTime.Now.Year); } } |
Kind regards, Daniel