You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用A.CallTo模拟context.T.AddAsync并正确创建EntityEntry<Request>返回对象

How to Mock EntityEntry for Testing EF Core's AddAsync Method

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:23:13