dennisdoomen / dennisdoomen/mockly

[API Proposal]: Add request-driven response templating (BodyAs<T>, path/query accessors, responder overloads)

Open
#181 0 comments 0 reactions 0 assignees View on GitHub
api-approved enhancement
Dominant language
C#
Stars
40
Forks
9
Avg merge
2d 1h
Merged PRs (30d)
13

Description

## Motivation

`RespondsWith(Func)` can express anything, but it is verbose for the two most common cases: echoing part of the request body back, and reflecting a path segment (an id) into the response.

Today that means building an `HttpResponseMessage` by hand, deserializing `RequestInfo.Body` yourself, and picking the id out of `Uri.AbsolutePath` with string surgery.

## Proposed API

Two additions that between them cover most of it.

**1. Richer `RequestInfo` accessors:**

```csharp
req.BodyAs(); // deserialize using the mock's JsonSerializerOptions
req.PathSegment(2); // "/api/users/123" -> "123"
req.QueryValue("page");
req.RouteValue("id"); // if a template was supplied to WithPath
```

**2. Responder overloads on the JSON/content methods, so no `HttpResponseMessage` plumbing is needed:**

```csharp
mock.ForPost("/api/users")
.RespondsWithJsonContent(HttpStatusCode.Created,
req => new { Id = Guid.NewGuid(), Name = req.BodyAs().Name });

mock.ForGet("/api/users/*")
.RespondsWithJsonContent(req => new { Id = req.PathSegment(2), Status = "active" });
```

## Notes

- `BodyAs()` should honour the options passed to `Using(JsonSerializerOptions)`.
- A string-templating alternative (`"{{path[2]}}"`) was considered, but typed lambdas fit the library's style better and stay refactor-safe.
- Core package change, so it needs API approval and an `AcceptApiChanges` run.

Contributor guide

Open the contributing guide

Research direction

Start by locating RequestInfo, RespondsWithJsonContent, RespondsWith, ForGet/ForPost, and Using(JsonSerializerOptions) in the core package. Review the existing API shape and run the AcceptApiChanges check mentioned in the issue. Done means the proposed accessors and responder overloads are designed, implemented, tested, and approved as core API changes.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
api, testing
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.