2011-12-15 40 views
1

我是Pex的新手,我无法看到如何将它与机器相关的例程(如DateTime.Now和File.Exists())一起使用。我如何让Pex处理函数使用DateTime.Now或File.Exists

我有一个功能,用于显示截止日期时间与时区偏移。

public class CommonDateTime 
{ 
    public static string ConvertToLongStringWithGmtOffset(DateTime cutoffData) 
    { 
     return String.Format(
      "{0} {1} GMT (local time is {2})", 
      cutoffData.ToLongDateString(), 
      cutoffData.ToShortTimeString(), 
      DateTime.Now.ToString("zzz"), // here is the problem... 
      CultureInfo.InvariantCulture); 
    } 
} 

我有得到由Pex的资源管理器

[PexClass(typeof(CommonDateTime))] 
[TestFixture] 
public partial class CommonDateTime_Test 
{ 
    /// <summary>Test stub for ConvertToLongStringWithGmtOffset(DateTime)</summary> 
    [PexMethod] 
    public string ConvertToLongStringWithGmtOffset(DateTime _cutOffData) 
    { 
     string result = CommonDateTime.ConvertToLongStringWithGmtOffset(_cutOffData); 
     return result; 
    } 
} 

产生然而,这产生测试其是机器特有的一个的Pex参数化测试 - 当机器处于非GMT时区失败。

public partial class CommonDateTime_Test 
{ 
    [Test] 
    [PexGeneratedBy(typeof(CommonDateTime_Test))] 
    public void ConvertToLongStringWithGmtOffset156() 
    { 
     string s; 
     s = this.ConvertToLongStringWithGmtOffset(default(DateTime)); 
     PexAssert.AreEqual<string> 
      ("Monday, January 01, 0001 12:00 AM GMT (local time is +00:00)", s); 
    } 
} 

在这种情况下我该怎么办?我可以告诉它跳过浏览函数,如DateTime.Now或File.Exists()函数。或者我可以告诉它总是以某种方式使用特定时区?

回答

3

这就是Moles项目的用途。它可以让你基本上嘲弄任何东西,包括像DateTime.Now这样的内置静态函数。

相应的 'Moled' 的代码会是这个样子:

[PexMethod] 
public string ConvertToLongStringWithGmtOffset(DateTime _cutOffData) 
{ 
    MDateTime.NowGet =() => /* some value */; 

    string result = CommonDateTime.ConvertToLongStringWithGmtOffset(_cutOffData); 
    return result; 
} 

Here's a longer tutorial其实际使用DateTime.Now作为例子。