简体   繁体   English

您如何最好地处理带有日期的测试?

[英]How do you best handle tests with dates?

I am using a Repository pattern with filters in my MVC application. 我在MVC应用程序中使用带有过滤器的存储库模式。 The project displays a list of transactions where I can specify a date period to get a subset of transactions, or specify a specific date to get transactions for that date (including year, year/month, and year/month/day views). 该项目显示了一个交易列表,我可以在其中指定一个日期周期以获取交易的子集,或者指定一个特定的日期以获取该日期的交易(包括年,年/月和年/月/日视图)。

I also have functionality for paging getting the next and previous transactions based on what kind of view we are looking at. 我还具有基于我们正在查看的视图进行分页获取下一个和上一个事务的功能。 For example if we are selecting all transactions for a given year/month then I find the next previous and next transactions based on this date period. 例如,如果我们选择给定年/月的所有交易,那么我会根据该日期周期找到下一个上一个和下一个交易。

How would you go about unit testing for such a thing... here is my mock transaction test 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 is an example test scnenario. 这是测试程序示例。

[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 then this is my filter 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;
}

您需要一种.Add (或CreateTransaction )的变体形式,使您可以“注入”(假)日期,正是出于这种测试目的。

您可以使用“ 如何对机器的特定行为进行单元测试? ”中所述的相同技术,以特定日期进行注入/使用/创建/测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM