|
| 1 | +using InertiaCore; |
| 2 | +using InertiaCore.Extensions; |
| 3 | +using InertiaCore.Ssr; |
| 4 | +using Microsoft.AspNetCore.Http; |
| 5 | +using Microsoft.AspNetCore.Http.Features; |
| 6 | +using Microsoft.AspNetCore.Mvc; |
| 7 | +using Microsoft.AspNetCore.Mvc.Abstractions; |
| 8 | +using Microsoft.AspNetCore.Routing; |
| 9 | +using Microsoft.Extensions.Options; |
| 10 | +using Moq; |
| 11 | + |
| 12 | +namespace InertiaCoreTests; |
| 13 | + |
| 14 | +public partial class Tests |
| 15 | +{ |
| 16 | + private IResponseFactory _factory = null!; |
| 17 | + |
| 18 | + /// <summary> |
| 19 | + /// Setups Inertia response factory for the tests. |
| 20 | + /// </summary> |
| 21 | + [SetUp] |
| 22 | + public void Setup() |
| 23 | + { |
| 24 | + var contextAccessor = new Mock<IHttpContextAccessor>(); |
| 25 | + var httpClientFactory = new Mock<IHttpClientFactory>(); |
| 26 | + |
| 27 | + var gateway = new Gateway(httpClientFactory.Object); |
| 28 | + var options = new Mock<IOptions<InertiaOptions>>(); |
| 29 | + options.SetupGet(x => x.Value).Returns(new InertiaOptions()); |
| 30 | + |
| 31 | + _factory = new ResponseFactory(contextAccessor.Object, gateway, options.Object); |
| 32 | + } |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Prepares ActionContext for usage in tests. |
| 36 | + /// </summary> |
| 37 | + /// <param name="headers">Optional request headers.</param> |
| 38 | + /// <param name="sharedData">Optional Inertia shared data.</param> |
| 39 | + /// <param name="modelState">Optional validation errors dictionary.</param> |
| 40 | + private static ActionContext PrepareContext(HeaderDictionary? headers = null, InertiaSharedData? sharedData = null, |
| 41 | + Dictionary<string, string>? modelState = null) |
| 42 | + { |
| 43 | + var request = new Mock<HttpRequest>(); |
| 44 | + request.SetupGet(r => r.Headers).Returns(headers ?? new HeaderDictionary()); |
| 45 | + |
| 46 | + var response = new Mock<HttpResponse>(); |
| 47 | + response.SetupGet(r => r.Headers).Returns(new HeaderDictionary()); |
| 48 | + |
| 49 | + var features = new FeatureCollection(); |
| 50 | + if (sharedData != null) |
| 51 | + features.Set(sharedData); |
| 52 | + |
| 53 | + var httpContext = new Mock<HttpContext>(); |
| 54 | + httpContext.SetupGet(c => c.Request).Returns(request.Object); |
| 55 | + httpContext.SetupGet(c => c.Response).Returns(response.Object); |
| 56 | + httpContext.SetupGet(c => c.Features).Returns(features); |
| 57 | + |
| 58 | + var context = new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor()); |
| 59 | + |
| 60 | + if (modelState == null) return context; |
| 61 | + |
| 62 | + foreach (var (key, value) in modelState) |
| 63 | + { |
| 64 | + context.ModelState.AddModelError(key, value); |
| 65 | + } |
| 66 | + |
| 67 | + return context; |
| 68 | + } |
| 69 | +} |
0 commit comments