如何使用A.CallTo模拟context.T.AddAsync并正确创建EntityEntry<Request>返回对象
I get it, trying to mock EntityEntry<Request> directly can be tricky because EF Core doesn't expose a public constructor for this type—it's designed to be instantiated only by the DbContext internally. Let's fix this with FakeItEasy (since your test code uses it) so you can properly mock the return value of AddAsync.
Step 1: Create a Fake EntityEntry
Instead of trying to new an instance, use FakeItEasy to generate a mock of EntityEntry<Request>, then configure its properties to match your test scenario:
// Create a fake EntityEntry<Request> var _addAsyncResponse = A.Fake<EntityEntry<Request>>(); // Set the State property to match your business logic's expected value // For the "Added" success path, set it to EntityState.Added A.CallTo(() => _addAsyncResponse.State).Returns(EntityState.Added); // Optional: If your code uses the Entity property later, mock that too // var testRequestEntity = new Request { /* populate with test data */ }; // A.CallTo(() => _addAsyncResponse.Entity).Returns(testRequestEntity);
Step 2: Wire Up the Fake to AddAsync
Update your existing FakeItEasy setup to use this mock, and make sure to handle the CancellationToken flexibly with A<CancellationToken>.Ignored (this matches any cancellation token passed in, which is better than hardcoding new CancellationToken()):
A.CallTo(() => _context.AddAsync(A<Request>.Ignored, A<CancellationToken>.Ignored)) .Returns(_addAsyncResponse);
Testing Both Logic Branches
To cover the failure path in your business code, just adjust the mocked State property:
// Mock a failed AddAsync scenario A.CallTo(() => _addAsyncResponse.State).Returns(EntityState.Unchanged);
This lets you fully validate how your code handles both success and failure cases of the AddAsync call.
内容的提问来源于stack exchange,提问作者Ayesh Nipun

