I'm working on an application (a web application, asp.net and c#) which is datetime-dependent, so, based on the current date, it will launch forms for the logged user to fill in.
I've been thinking about how we're going to simulate real usage of the application, for debugging and testing purposes.
So I'm talking about replacing all those:
DateTime currentDate = DateTime.Now;
with something like:
DateTime currentDate = MyDateClass.GetCurrentDate();
And then I'll have a class:
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;
}
}
allowing me to set the current data, by invoking the SetCurrentDate method, for example, in the code-behind of a link button and a calendar input.
Question is... how should I exactly store the DateTime variable, throughout all the application? I can't work with the session in this class, right? Should I work with the Thread?
Well, ideas are appreciated :) Thanks in advance for your suggestions!
Some updating on my question:
I ran into this post: What's a good way to overwrite DateTime.Now during testing?
Just like you provided here with your answers (thank you!), great tips for good code organization, for both development and testing purposes, that I will definitely be considering in the time to follow.
I still have the same question though: how will I "hold" the datetime value?
Right now, I went with creating a single cell table in the data base to maintain "my" datetime value.
I have a开发者_StackOverflow static class with a GetCurrentDate and a SetCurrentDate function:
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);
// ...
}
}
However, storing the date in the database, with a table created and used just for debugging, doesn't seem like an elegant solution...
Create an interface:
public interface ITimeProvider
{
DateTime Now { get; }
}
Then you can create two subclasses - one for production usage which just returns the current time using DateTime.Now
, and another where you can manually set the time for testing purposes. Use dependency injection to provide the appropriate implementation.
Can you use Rhino Mocks (or similar) to spoof the current date time in your unit tests, rather than writing code just for testing purposes?
精彩评论