unit-testing - 如何在 Entity Framework 中使用 "Pex and Moles"库?

标签 unit-testing entity-framework pex-and-moles

这是一个艰难的因为我认为没有太多人使用 Pex & Moles(尽管 Pex 是一个非常棒的产品 - 比任何其他单元测试工具都要好得多)

我有一个 数据该项目具有一个非常简单的模型,只有一个实体 ( DBItem )。我还写了一个 DBRepository在这个项目中,操纵这个 EF 模型。 Repository 有一个方法叫做 GetItems()返回业务层项目列表( BLItem ),看起来与此类似(简化示例):

public IList<BLItem> GetItems()
{
    using (var ctx = new EFContext("name=MyWebConfigConnectionName"))
    {
        DateTime limit = DateTime.Today.AddDays(-10);
        IList<DBItem> result = ctx.Items.Where(i => i.Changed > limit).ToList();
        return result.ConvertAll(i => i.ToBusinessObject());
    }
}

所以现在我想为这个特定的方法创建一些单元测试。我正在使用 Pex & Moles .我为我的 EF 对象上下文创建了痣和 stub 。

我想编写参数化单元测试(我知道我首先编写了我的生产代码,但我必须这样做,因为我正在测试 Pex & Moles)来测试此方法是否返回有效的项目列表。

这是我的测试课:
[PexClass]
public class RepoTest
{
    [PexMethod]
    public void GetItemsTest(ObjectSet<DBItem> items)
    {
        MEFContext.ConstructorString = (@this, name) => {
             var mole = new SEFContext();
        };

        DBRepository repo = new DBRepository();
        IList<BLItem> result = repo.GetItems();

        IList<DBItem> manual = items.Where(i => i.Changed > DateTime.Today.AddDays(-10));

        if (result.Count != manual.Count)
        {
            throw new Exception();
        }
    }
}

然后我为这个特定的参数化单元测试运行 Pex Explorations,但我收到错误 超出路径边界 . Pex 通过提供 null 开始此测试到这个测试方法(所以 items = null )。这是 Pex 正在运行的代码:
[Test]
[PexGeneratedBy(typeof(RepoTest))]
[Ignore("the test state was: path bounds exceeded")]
public void DBRepository_GetTasks22301()
{
    this.GetItemsTest((ObjectSet<DBItem>)null);
}

这是 Pex 提供的附加评论:

The test case ran too long for these inputs, and Pex stopped the analysis. Please notice: The method Oblivious.Data.Test.Repositories.TaskRepositoryTest.b__0 was called 50 times; please check that the code is not stuck in an infinite loop or recursion. Otherwise, click on 'Set MaxStack=200', and run Pex again.

Update attribute [PexMethod(MaxStack = 200)]





我这样做是否正确?我应该改用 EFContext stub 吗?我是否必须向测试方法添加其他属性,以便 Moles 主机运行(我现在不确定它是否会运行)。我只跑 Pex & Moles。没有 VS 测试或 nUnit 或其他任何东西。

我想我可能应该为 Pex 设置一些限制,它应该为这个特定的测试方法提供多少项目。

最佳答案

Moles 并非旨在测试具有外部依赖关系的应用程序部分(例如文件访问、网络访问、数据库访问等)。相反,Moles 允许您模拟应用程序的这些部分,以便您可以对没有外部依赖项的部分进行真正的单元测试。

所以我认为你应该模拟你的 EF 对象和查询,例如,通过创建内存列表并让查询方法根据任何相关标准从这些列表中返回假数据。

关于unit-testing - 如何在 Entity Framework 中使用 "Pex and Moles"库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3764922/

相关文章:

node.js - Jest + MockImplementationOnce + 没有第二次工作

.net - 在多个服务之间共享 dbcontext 的最佳方式是什么?

c# - Entity Framework 中的条件包含()

.net - 如何对网络连接进行单元测试?

unit-testing - 在 Controller 单元测试中 stub 自定义TagLib方法

unit-testing - 如何使用 LLBLGen 进行模拟

python - 如何模拟 boto3 的 StreamingBody 对象以在 Python 中使用 BytesIO 进行处理?

c# - Entity Framework - 为集合中的成员加载特定的导航属性

c# - 如何告诉 Pex 不要 stub 具有具体实现的抽象类