了解如何编写单元测试代码

时间:2015-02-12 14:02:01

标签: c# .net entity-framework unit-testing testing

我有我的服务层使用Entity Framework 6.我试图模拟实体框架,没有太大成功(前进1步,后退2步),但我认为球现在已经落在了我的脑海中。我以前从未真正为单元测试创​​建代码,所以它有点新。

我是否正确思考,只需将代码编写成更多可测试的代码"而不是功能/行动。

因此,例如,我的AddAsync方法看起来像这样(非常基本,保持简单)

public override async Task<int> AddAsync(FieldGroup t)
{
    // new groups are added to the last position in the location
    var groupCount = await _context.FieldGroups
        .OrderBy(e => e.Position)
        .CountAsync();

    // if there is no groups, set position to 1
    // else if there is set it equal to the last position + 1
    if (groupCount == 0)
    {
        t.Position = 1;
    }
    else
    {
        t.Position = (short)(groupCount + 1);
    }

    return await base.AddAsync(t);
}

基本上,当我添加我的FieldGroup时,我需要获得正确的位置编号以插入它并设置位置。

为了使这个单元可以测试更多&#34;,我应该将代码从AddAsync函数中移出到另一个接受数字作为参数的函数中。像这样的东西

public override async Task<int> AddAsync(FieldGroup t)
{
    // new groups are added to the last position in the location
    var groupCount = await _context.FieldGroups
        .Where(e => e.ModuleId == t.ModuleId && e.Location == t.Location)
        .WhereNotDeleted()
        .OrderBy(e => e.Position)
        .CountAsync();

    t.Position = GetNextPositionNumber(groupCount);

    return await base.AddAsync(t);
}

public short GetNextPositionNumber(int groupCount)
{
    // if there is no groups in this location, set position to 1
    // else if there is set it equal to the last position + 1
    if (groupCount == 0)
    {
        return 1;
    }
    else
    {
        return (short)(groupCount + 1);
    }
}

现在可以在GetNextPositionNumber方法上运行测试,我知道更长时间需要实体框架来获取任何内容。

现在,如果你这样做,显然我现在正在测试GetNextPositionNumber方法,而不是AddAsync方法,但是测试AddSync方法应该稍后进行一些集成测试,这将确保整个方法有效,并且我可以使用EF和测试数据库来测试它。

这是对的,还是我完全忽略了这一点?

如果这是错误的,你如何编写测试并模拟EF?每当我解决问题时,我似乎都会碰壁。就像首先能够使用Async模拟EF,然后在实体上设置状态,然后使用Include关键字来加载实体。

0 个答案:

没有答案