Skip to content

Commit

Permalink
fix: add overload for ctx, cts and builder
Browse files Browse the repository at this point in the history
  • Loading branch information
skwasjer committed Jan 2, 2023
1 parent 5f9ca8e commit 06ca776
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/MockHttp/Extensions/IRespondsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,22 @@ public static TResult Respond<TResult>(this IResponds<TResult> responds, Func<Ht
return responds.RespondUsing(new ResponseFuncStrategy((request, ct) => Task.FromResult(response(request, ct))));
}

/// <summary>
/// Specifies a function that returns the response for a request.
/// </summary>
/// <param name="responds"></param>
/// <param name="with">The function that provides the response message to return for given request.</param>
public static TResult Respond<TResult>(this IResponds<TResult> responds, Action<MockHttpRequestContext, CancellationToken, IResponseBuilder> with)
where TResult : IResponseResult
{
if (responds is null)
{
throw new ArgumentNullException(nameof(responds));
}

return responds.RespondUsing(new RequestSpecificResponseBuilder(with));
}

/// <summary>
/// Specifies a strategy that returns the response for a request.
/// </summary>
Expand Down Expand Up @@ -98,27 +114,27 @@ public static TResult Respond<TResult>(this IResponds<TResult> responds, Action<
public static TResult Respond<TResult>(this IResponds<TResult> responds, Action<MockHttpRequestContext, IResponseBuilder> with)
where TResult : IResponseResult
{
if (responds is null)
if (with is null)
{
throw new ArgumentNullException(nameof(responds));
throw new ArgumentNullException(nameof(with));
}

return responds.RespondUsing(new RequestSpecificResponseBuilder(with));
return responds.Respond((ctx, _, builder) => with(ctx, builder));
}

private sealed class RequestSpecificResponseBuilder : IResponseStrategy
{
private readonly Action<MockHttpRequestContext, IResponseBuilder> _with;
private readonly Action<MockHttpRequestContext, CancellationToken, IResponseBuilder> _with;

public RequestSpecificResponseBuilder(Action<MockHttpRequestContext, IResponseBuilder> with)
public RequestSpecificResponseBuilder(Action<MockHttpRequestContext, CancellationToken, IResponseBuilder> with)
{
_with = with ?? throw new ArgumentNullException(nameof(with));
}

public Task<HttpResponseMessage> ProduceResponseAsync(MockHttpRequestContext requestContext, CancellationToken cancellationToken)
{
var builder = new ResponseBuilder();
_with(requestContext, builder);
_with(requestContext, cancellationToken, builder);
IResponseStrategy responseStrategy = builder.Build();
return responseStrategy.ProduceResponseAsync(requestContext, cancellationToken);
}
Expand Down

0 comments on commit 06ca776

Please sign in to comment.