一键导入
stateful-mocks
Testing patterns for simulating sequential calls and race conditions using Moq stateful callbacks
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Testing patterns for simulating sequential calls and race conditions using Moq stateful callbacks
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Authorization Code Flow for web applications using MSAL.NET confidential client to sign in users and access APIs on their behalf
Handle MSAL distributed token cache collisions and stale entries in ASP.NET Core applications
On-Behalf-Of (OBO) Flow for web APIs to call downstream APIs while preserving user identity in MSAL.NET
{what this skill teaches agents}
Review API DTO implementations for contract/domain separation, mapping patterns, and REST compliance
This skill should be used when the user asks to "build a feature", "fix a bug", "implement something", "start a dev cycle", types "/dev", or describes a software task that requires design, implementation, testing, and shipping. Orchestrates the full software development lifecycle from interrogation through shipping, with self-learning that improves over time.
| name | stateful-mocks |
| description | Testing patterns for simulating sequential calls and race conditions using Moq stateful callbacks |
| domain | testing |
| confidence | high |
| source | earned (Issue #708 regression testing) |
When testing scenarios where the same method is called multiple times with different outcomes (e.g., double-submit, race conditions, retry logic), you need to simulate state changes in your mocks. This is particularly useful for:
Project: JJGNET Broadcasting
Framework: xUnit + Moq 4.20.72
Use Case: Issue #708 - Testing Web controller behavior when double-submit occurs
Use a local counter variable to track call count and return different results:
[Fact]
public async Task Method_DuplicateCall_HandlesSecondCallFailure()
{
// Arrange
var callCount = 0;
_mockService
.Setup(s => s.AddSomething(It.IsAny<int>(), It.IsAny<int>()))
.ReturnsAsync(() =>
{
callCount++;
if (callCount == 1)
{
return new SuccessResult(); // First call succeeds
}
throw new ConflictException("Duplicate"); // Second call fails
});
// Act
var firstResult = await _controller.Action(); // Call 1: success
var secondResult = await _controller.Action(); // Call 2: error
// Assert
Assert.IsType<RedirectResult>(firstResult);
Assert.Contains("success", _controller.TempData["Message"]);
Assert.IsType<RedirectResult>(secondResult);
Assert.Contains("Duplicate", _controller.TempData["ErrorMessage"]);
}
For more complex sequences, use a queue of responses:
var responses = new Queue<Result>(new[] {
new Result { Success = true },
new Result { Success = false, Error = "Conflict" },
new Result { Success = true } // Retry succeeds
});
_mockService
.Setup(s => s.Process())
.ReturnsAsync(() => responses.Dequeue());
Capture the state passed to the mock to verify it changes between calls:
var capturedStates = new List<State>();
_mockService
.Setup(s => s.Update(It.IsAny<State>()))
.Callback<State>(state => capturedStates.Add(state))
.ReturnsAsync(true);
// ... multiple calls ...
Assert.Equal(2, capturedStates.Count);
Assert.Equal("Initial", capturedStates[0].Status);
Assert.Equal("Updated", capturedStates[1].Status);
File: src/JosephGuadagno.Broadcasting.Web.Tests/Controllers/EngagementsControllerTests.cs
[Fact]
public async Task AddPlatform_Post_DuplicateAttempt_ShouldHandleHttpRequestException()
{
// Arrange - Simulates the double-submit scenario from issue #708
// First call succeeds, second call would fail with 409 Conflict
var viewModel = new EngagementSocialMediaPlatformViewModel
{
EngagementId = 42,
SocialMediaPlatformId = 1,
Handle = "@TestHandle"
};
var firstCallSucceeds = new EngagementSocialMediaPlatform
{
EngagementId = 42,
SocialMediaPlatformId = 1,
Handle = "@TestHandle"
};
var callCount = 0;
_engagementService
.Setup(s => s.AddPlatformToEngagementAsync(42, 1, "@TestHandle"))
.ReturnsAsync(() =>
{
callCount++;
if (callCount == 1)
{
return firstCallSucceeds;
}
throw new HttpRequestException("API returned 409 Conflict");
});
// Act - First call (succeeds)
var firstResult = await _controller.AddPlatform(viewModel);
// Assert first call
var firstRedirect = Assert.IsType<RedirectToActionResult>(firstResult);
Assert.Equal("Edit", firstRedirect.ActionName);
Assert.Equal("Platform added successfully.", _controller.TempData["SuccessMessage"]);
// Act - Second call (simulates double-submit, should be caught)
var secondResult = await _controller.AddPlatform(viewModel);
// Assert second call - Error should be caught and user-friendly message shown
var secondRedirect = Assert.IsType<RedirectToActionResult>(secondResult);
Assert.Equal("Edit", secondRedirect.ActionName);
Assert.Contains("409 Conflict", (string)_controller.TempData["ErrorMessage"]!);
}
Key Points:
callCount) tracks which call is executing.SetupSequence() for Exception CasesDon't:
_mock.SetupSequence(s => s.Method())
.ReturnsAsync(new Result())
.Throws(new Exception()); // Throws synchronously, not async!
Do:
_mock.Setup(s => s.Method())
.ReturnsAsync(() => callCount++ == 0 ? new Result() : throw new Exception());
Reason: .Throws() in SetupSequence doesn't work with async methods. Use callback-based logic instead.
Don't:
private int _sharedCallCount = 0; // Shared across tests!
[Fact]
public void Test1() { /* uses _sharedCallCount */ }
[Fact]
public void Test2() { /* uses _sharedCallCount */ }
Do:
[Fact]
public void Test1()
{
var callCount = 0; // Local to this test
// ...
}
Reason: xUnit doesn't guarantee test execution order. Shared state causes flaky tests.
Don't:
_mock.Setup(s => s.Method())
.ReturnsAsync(() => {
// 50 lines of complex business logic
// ...
});
Do:
Use stateful mocks when:
Don't use stateful mocks when:
.Setup() with fixed return value sufficessrc/JosephGuadagno.Broadcasting.Web.Tests/Controllers/EngagementsControllerTests.cs (lines 505-560).squad/decisions/inbox/tank-708-web-tests.md.squad/agents/tank/history.md (2026-04-13 session)