2010-11-03 49 views
1

我正在研究一个依赖于日期时间的应用程序(一个web应用程序,asp.net和c#),因此,根据当前日期,它将启动窗体为登录用户填写。如何调试时间依赖的应用程序? (使用当前日期时间变量而不是DateTime.Now)

我一直在考虑如何模拟应用程序的实际使用情况,以用于调试和测试目的。

所以,我说的是更换所有这些:

DateTime currentDate = DateTime.Now; 

的东西,如:

DateTime currentDate = MyDateClass.GetCurrentDate(); 

然后,我将有一个类:

public class MyDateClass 
{ 
    private DateTime _currentDate; 

    public DateTime GetCurrentDate() 
    { 
     // get the date, which may be different from DateTime.Now 
     return _currentDate; 
    } 

    public void SetCurrentDate(DateTime newCurrentDate) 
    { 
     // set the date to the value chosen by the user 
     _currentDate = newCurrentDate; 
    } 
} 

让我通过调用SetCurrentDate方法来设置当前数据,例如,在链接按钮和日历inp的代码后面UT。

问题是......我应该如何在所有应用程序中准确存储DateTime变量?我不能在这堂课上学习,对吧?我应该使用线程吗?

那么,想法赞赏:)在此先感谢您的建议!


对我的问题的一些更新:

我碰到了这个帖子:What's a good way to overwrite DateTime.Now during testing?

就像你与你的答案提供在这里(谢谢!),良好的代码组织伟大的秘诀,对于无论是开发还是测试目的,我都会在考虑的时候考虑。

虽然我仍然有同样的问题:我将如何“保留”日期时间值?

现在,我在数据库中创建一个单元格表以保持“我的”日期时间值。

我有一个GetCurrentDate和SetCurrentDate功能的静态类:

public static class DateManagement 
{ 
    public static DateTime GetCurrentDate() 
    { 
     // return DateTime.Now; 
     // OR: 
     // ... 
     // SqlCommand cmd = new SqlCommand("select Date from CurrentDate", conn); 
     // ... 
    } 

    public static void SetCurrentDate(DateTime newDate) // used only in debugging 
    { 
     // ... 
     // string insertStr = @"update CurrentDate set Date = '" + date + "'"; 
     // SqlCommand cmd = new SqlCommand(insertStr, conn); 
     // ... 
    } 
} 

然而,在数据库中存储的日期,以创造和公正的调试使用的表格,似乎并不像一个优雅解决方案...

+1

然后,如果你正在谈论我假设的会话,那么你正在创建一个Web应用程序? – Neil 2010-11-03 10:49:34

+1

您可以先开始制作MyDateClass静态。 – 2010-11-03 10:50:53

+0

是的,这是一个web应用程序(asp.net和c#,vs2008开发)。 – naruu 2010-11-03 11:04:25

回答

3

创建一个接口:

public interface ITimeProvider 
{ 
    DateTime Now { get; } 
} 

然后您可以创建两个子类 - 一个用于生产使用刚刚使用返回当前时间DateTime.Now,另一个可以手动设置测试时间的地方。使用dependency injection来提供适当的实施。

+0

嗯,这将是一个很好的方式来组织代码(不知道那些模式,看起来类似于工厂) 。然而,我的问题(也许我只是没有得到它......)是我将如何维护,保存,一个和唯一的日期时间变量? – naruu 2010-11-03 11:09:11

1

您可以使用Rhino Mocks(或类似的)来欺骗单元测试中的当前日期时间,而不是为了测试目的而编写代码?

+0

然而,这看起来很有趣,因为我现在只想控制“currentDateTime”,我宁愿不使用这个工具,但是现在想知道这些(不知道这些工具),所以我会保留他们考虑未来的发展和测试。 – naruu 2010-11-03 11:14:04

相关问题