gpt4 book ai didi

c# - 了解 Moq 的 Setup() 函数

转载 作者:行者123 更新时间:2023-11-30 20:41:40 25 4
gpt4 key购买 nike

我对 Setup() 有点困惑。

据我声明时的理解:

Mock<IUnitOfWork> uwork = new Mock<IUnitOfWork>();

我们正在创建一个模拟存储库,该存储库实际上 永远不会访问数据库。因为它从不接触数据库,所以我们必须给它一些模拟数据。

例如:

Question question = new Question {
Title = "General question",
Message = "Message body text..."
}

这是我有点困惑的地方。根据我的理解,我们正在告诉我们的 Mocked 存储库什么数据要返回以及在哪种情况下返回它。

                   // in this circumstance         // return this
uwork.Setup(i =. i.QuestionsRepository.GetById(1)).Returns(question)

此时,我们创建了一个 Controller 实例,并将 uwork.object 传递给 Controller ​​实例。当 Controller 调用(环境)方法时,我们的 Mock 存储库会生成我们指定的返回值。

问题

这是正确的吗? 如果不 在这里阻止我并纠正我。 如果是这样,那么为什么这样的事情不起作用,我该如何解决这个问题?

Controller :

uwork.QuestionRepository.GetAll().Where(l => l.Message_Id == id).ToList();

测试 Controller :

uwork.Setup(i => i.QuestionsRepository
.GetAll().Where(l => l.Message_Id == 1).ToList())
.Returns(questions);
// questions is a List<Question>

我得到一个异常:

An exception of type 'System.NotSupportedException' occurred in Moq.dll but was not handled in user code

Additional information: Expression references a method that does not belong to the mocked object: i => i.LegalInquiryRepository.GetAll().Where(l => l.legalCommunication_Id ==

最佳答案

你得到那个异常是因为你试图设置一个方法(Where)属于模拟(uwork).

您需要先设置i.QuestionRepository 属性,然后设置GetAll 方法。

Where 方法(假设它是为 IQueryable 定义的方法)不能被模拟,因为它是静态的 - 但没关系。只需确保源集合具有正确的元素,Where 就会选择它们。

var questionsRepoMock = //...

uwork.SetupGet(i => i.QuestionsRepository).Returns(questionsRepoMock.Object);


questionsRepoMock.Setup(r => r.GetAll())
.Returns(questions);

关于c# - 了解 Moq 的 Setup() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32144504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com