如何模拟 DbUpdateConcurrencyException

How to mock DbUpdateConcurrencyException

我正在尝试在我的服务中模拟函数以抛出 DbUpdateConcurrencyException。我的代码只需要检查 DbUpdateConcurrencyException 类型的异常,不需要读取构造函数要求的异常消息或条目列表。

我想通过为 DbUpdateConcurrencyException 调用无参数构造函数来设置 Mock,但这在 EFCore 中不存在。

var mockService = new Mock<IMyService>();
mockService.Setup(service => service.UpdateFooAsync(It.IsNotNull<Data.Foo>())).Throws(new DbUpdateConcurrencyException());

我试过使用一些参数调用 new DbUpdateConcurrencyException(),但是对参数进行了一些检查,阻止我使用 null/empty 数据执行此操作。

new DbUpdateConcurrencyException(null, null) 给出:

Message: System.ArgumentNullException : Value cannot be null.
Parameter name: entries

new DbUpdateConcurrencyException("", new List<IUpdateEntry>()) 给出:

Message: System.ArgumentException : The collection argument 'entries' must contain at least one element.

在 Moq 中有没有一种方法可以模拟 DbUpdateConcurrencyException 而不必通过构造函数的检查?

根据您在评论中分享的文档,您应该使用带有两个参数的 ctor。诀窍是提供 not null string and not empty List<IUpdateEntry>moq 可以帮助你,例如

new DbUpdateConcurrencyException(string.Empty, new List<IUpdateEntry>{Mock.Of<IUpdateEntry>()});