How to mock DbUpdateConcurrencyException

entity-framework-core moq


I'm trying to mock function in my service to throw a DbUpdateConcurrencyException. My code only needs to check for an exception of type DbUpdateConcurrencyException and doesn't need to read the exception message or list of entries that the constructor asks for.

I want to set up the Mock by calling a parameter-less constructor for DbUpdateConcurrencyException, but that doesn't exist in EFCore.

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

I've tried calling new DbUpdateConcurrencyException() with some parameters, but there's some checks that happen on the parameters that prevents me from doing this with null/empty data.

new DbUpdateConcurrencyException(null, null) gives:

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

new DbUpdateConcurrencyException("", new List<IUpdateEntry>()) gives:

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

Is there a way in Moq that I can mock the DbUpdateConcurrencyException without having to go through the checks that the constructor has?

7/9/2019 5:10:38 PM

Accepted Answer

Based on docs you have shared in comments you should use ctor with two parameters. The trick is to provide not null string and not empty List<IUpdateEntry>, moq could help you with that, e.g.

new DbUpdateConcurrencyException(string.Empty, new List<IUpdateEntry>{Mock.Of<IUpdateEntry>()});
7/9/2019 5:46:54 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow