这种情况下Assert.AreSame是否应返回true? [英] Should this case of Assert.AreSame return true?

查看:226
本文介绍了这种情况下Assert.AreSame是否应返回true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试已创建的存储库模式,并使用Moq包模拟对象.我想测试2个对象的引用,但结果让我感到惊讶.这是测试:

I am testing a repository pattern I have created and I use Moq package to mock my objects. I wanted to test references from 2 objects, but the result kind of surprises me. Here is the test:

Mock<Repository<Web_Documents>> moqRepo;
Mock<Repository<Web_Documents>> moqRepo2;

public void ObjEqGetTest()
{
    //context is DBContext and has been initialized using [TestInitialize] annotation
    moqRepo = new Mock<Repository<Web_Documents>>(context);
    moqRepo2 = new Mock<Repository<Web_Documents>>(context);
    var test = moqRepo.Object.Get(1L);
    var test2 = moqRepo2.Object.Get(1L);
    Assert.AreSame(test, test2);
}

我的Get方法返回:

return entities.SingleOrDefault(predicate)

predicate正在使用Expression构建器创建(如果需要,我可以添加代码).

predicate being created using Expression builder (I can add code if needed).

当我创建了两个不同的对象时,为什么此Assert返回true?

Why does this Assert return true, when I have created two differents objects?

每当您从数据库中获取数据时(因为它指向所使用的模型),Get方法是否返回相同的引用?

Is it that the Get method returns the same reference whenever you fetch data from a DB (since it points to the model being used)?

感谢您的帮助!

编辑 @CodeCaster说,模拟存储库将在我提出的请求中返回null.但是,当我验证表Web_Documents中的值时,断言将返回true.让我演示一下:

EDIT @CodeCaster said Mocking repos will return null in the request I made. But When I verify values in my table Web_Documents, Assertions return true. Let me demonstrate this :

public void IdExistsGetTest()
{
    moqDoc = new Mock<Repository<Web_Documents>>(context);
    var testDoc = moqDoc.Object.Get(1L);
    Assert.AreEqual(testDoc.NomDocument, "Ajouter une catégorie");
}

此测试成功,并且在Web_Documents中,ID = 1处的行具有NomDocument = "Ajouter une catégorie".

This test is successful, and in Web_Documents, the row at ID = 1 has NomDocument = "Ajouter une catégorie".

推荐答案

我假设context是实体框架上下文.您在两个存储库之间共享它,因此在不同存储库上的两个查询将返回相同的实体,因为Entity Framework在上下文中缓存"了实体(在某种意义上).当看到查询返回已附加到上下文的实体时(在这种情况下-由第一个查询返回),它将为第二个查询再次返回相同的实体(如果实体具有相同的主键,则它们是相同"的)类型).

I assume context is Entity Framework context. You share it between your two repositories, so your two queries on different repositories will return the same entity, because Entity Framework "caches" entities (in certain sense) inside the context. When it sees your query returns entity which is already attached to the context (in this case - returned by first query) - it will return the same entity again for the second one (entities are "same" if they have the same primary key and type).

这篇关于这种情况下Assert.AreSame是否应返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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