单元测试双向EF关系 [英] Unit testing a two way EF relationship

查看:144
本文介绍了单元测试双向EF关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小型练习项目来提高我的单元测试技能。我正在使用实体框架代码。



我正在使用一个FakeDBSet,它适用于简单的实体列表。当实体树被归还时,事情并不那么好。特别是双向关系并不保留,因为这是实体框架的一部分魔法。



我有两个类:

  public class Book 
{
public virtual ICollection< Review>点评{get; set;}
}

public class Review
{
public virtual Book Book {get;设置;}
}

如果我将该书设置为审查,则评论不添加到书的评论集合。它使用EF,而不是在我的假版本。



有没有办法模拟这个行为,还是我不应该依靠EF来实现双向关系?或者嘲笑数据上下文浪费时间?

解决方案

这实际上是一个很常见的问题(而没有真正的好答案)。有一个过程发生在EF内部,称为fixup,它在检测更改循环(在添加/删除和其他一些更改中触发的循环)中运行。这将评估您的模型中的反向链接。当您开始嘲笑您的上下文时,您将会失去检测更改循环,从而导致修复。



过去,我了解了此特定限制我的嘲笑,并确保我以正确的方式执行我的设置代码在代码中有意义(这让我们面对它是非常不理想的)。另一个选择是在您的单元测试中使用某种形式的真实轻型数据库,并继续使用EF。


I'm doing a small practice project to improve my unit testing skills. I'm using Entity Framework Code First.

I'm using a FakeDBSet, which works well for simple lists of entities. When entity trees are returned things aren't so nice. In particular two way relationships aren't maintained as this is part of the Entity Framework magic.

I have two classes:

public class Book
{
    public virtual ICollection<Review> Reviews {get; set;}
}

public class Review
{
    public virtual Book Book { get; set;}
}

If I set the book for a review, the review does not get added to the book's review collection. It does when using EF, but not in my fake version.

Is there a way mock this behaviour, or should I not rely on EF to implement two way relationships? Or is mocking the data context just a waste of time?

解决方案

This is actually a pretty common problem (and one without a really good answer). There is a process which happens inside of EF called fixups which runs inside the detect changes loop (the one that triggers on add/remove and a few other changes). This evaluates backlinks in your model. When you start mocking your context you are going to lose that detect changes loop and hence the fixups.

In the past I've gotten around this by understanding this particular limitation of my mocks and making sure i do my setup code in the correct way to make sense in the code (which lets face it is pretty un-ideal). The other option here is to go to some form of real lightweight database in your unit tests and keep using EF.

这篇关于单元测试双向EF关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆