What's the best way to run tests with dates?

I am using repository pattern with filters in my MVC application. The project displays a list of transactions in which I can specify a date period to get a subset of transactions, or specify a specific date to receive transactions for that date (including year, year / month, and year / month / day).

I also have a function for paging to receive the next and previous transactions based on which view we are looking at. For example, if we select all transactions for a given year / month, I find the next previous and next transactions based on that period.

How would you unit test for such a thing ... here is my fancy test transaction repository.

public class TestTransactionsRepository: ITransactionsRepository
{
    private IList <Transaction> db;

    public TestTransactionsRepository ()
    {
        db = new List <Transaction> ();

        int i = 0;

        for (; i <10; i ++)
        {
            db.Add (CreateTransaction (i, 3));
        }

        for (; i <25; i ++)
        {
            db.Add (CreateTransaction (i, i));
        }

        for (; i <80; i ++)
        {
            db.Add (CreateTransaction (i, 5));
        }
    }

    private Transaction CreateTransaction (int id, int accountID)
    {
        return new Transaction
        {
            ID = id,
            AccountID = accountID,
            Date = ??
        };
     }
}

Here's a sample test case.

[TestMethod]
public void TransactionsRepository_Get_With_Filter_Between_ThisDate_
And_ThatDate_Returns_xx_Transactions ()
{
    IList <Transaction> transactions = TransactionsRepository.Get ()
                                        .Between (thisDate, thatDate)
                                        .ToList ();

    Assert.AreEqual (xx, transactions.Count);
}

And this is my filtering method

public static IQueryable <Transaction> Between (
this IQueryable <Transaction> qry, DateTime startDate, DateTime endDate)
{
    return from t in qry
           where t.Date> = startDate && t.Date <= endDate
           select t;
}
0


a source to share


2 answers


You need a form form .Add

(or CreateTransaction

) that allows you to "enter" a (fake) date for just such testing purposes.



+1


a source


You can use the same techniques as described in How to unit test a specific machine behavior? "to enter / use / create / test with specific dates.



0


a source







All Articles