From 7a37d1f3f06b51c66f58e9386b76fdd8f6d9d9c7 Mon Sep 17 00:00:00 2001 From: mjeldreth <112119461+mjeldreth@users.noreply.github.com> Date: Thu, 25 Aug 2022 14:56:58 -0400 Subject: [PATCH] Fixed GetEnumerator() method on mock The Mock needs to be configured to call the underlying collection's `GetEnumerator()` method every time it is invoked. As it is currently written, the method is only invoked once (during setup) to get a single value and that value is returned each time `GetEnumerator()` is called. This causes issues if the underlying data collection is changed by adding and/or removing items. Doing so results in the enumerator becoming stale and causes Invalid Operation Exceptions if you try to iterate through the IQueryable or call extension methods like `ToList()` or `ToArray()` --- entity-framework/ef6/fundamentals/testing/mocking.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/entity-framework/ef6/fundamentals/testing/mocking.md b/entity-framework/ef6/fundamentals/testing/mocking.md index b006bfd951..7ccff0c140 100644 --- a/entity-framework/ef6/fundamentals/testing/mocking.md +++ b/entity-framework/ef6/fundamentals/testing/mocking.md @@ -207,7 +207,7 @@ namespace TestingDemo mockSet.As>().Setup(m => m.Provider).Returns(data.Provider); mockSet.As>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As>().Setup(m => m.ElementType).Returns(data.ElementType); - mockSet.As>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); + mockSet.As>().Setup(m => m.GetEnumerator()).Returns(() => data.GetEnumerator()); var mockContext = new Mock(); mockContext.Setup(c => c.Blogs).Returns(mockSet.Object); @@ -382,7 +382,7 @@ namespace TestingDemo mockSet.As>().Setup(m => m.Expression).Returns(data.Expression); mockSet.As>().Setup(m => m.ElementType).Returns(data.ElementType); - mockSet.As>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); + mockSet.As>().Setup(m => m.GetEnumerator()).Returns(() => data.GetEnumerator()); var mockContext = new Mock(); mockContext.Setup(c => c.Blogs).Returns(mockSet.Object);