RSCG – Ridge

RSCG – Ridge
 
 

name Ridge
nuget https://www.nuget.org/packages/Ridge/
link https://github.com/Melchy/Ridge
author Michal Motyčka

Generating test classes for controllers

 

This is how you can use Ridge .

The code that you start with is


<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.9" />
    <PackageReference Include="RidgeDotNet.AspNetCore" Version="2.0.1" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
  </ItemGroup>
	<PropertyGroup>
		<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
		<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
	</PropertyGroup>

</Project>


The code that you will use is


var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();
public partial class Program { }


using Microsoft.AspNetCore.Mvc;
using Ridge.AspNetCore.GeneratorAttributes;

namespace RidgeDemoWebApp.Controllers
{
    [GenerateClient]
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}


using Microsoft.AspNetCore.Mvc.Testing;
using RidgeDemoWebApp.Controllers;
using Xunit;

namespace TestRidgeApp;

[TestClass]
public class BasicTests 
{

    
    [TestMethod]
    public async Task CallControllerUsingRidge()
    {
       
        using var webApplicationFactory =
            new WebApplicationFactory<Program>()
                .WithRidge(); // add ridge dependencies to WebApplicationFactory
        var client = webApplicationFactory.CreateClient();
        // create instance of client generated by source generator
        var examplesControllerClient = new WeatherForecastControllerClient(client, webApplicationFactory.Services);

        var response = await examplesControllerClient.Get();

        Assert.IsTrue(response.IsSuccessStatusCode);
        Assert.AreEqual(5, response.Result.Count());
    }
}

 

The code that is generated is

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by the Ridge source generator
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS0419
using Ridge.AspNetCore;
using Ridge.AspNetCore.Serialization;
using Ridge.AspNetCore.Response;
using Ridge.AspNetCore.Parameters;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;

namespace RidgeDemoWebApp.Controllers
{
    /// <summary>
    /// Generated Api client. Calls <see cref="RidgeDemoWebApp.Controllers.WeatherForecastController" />
    /// </summary>
    public class WeatherForecastControllerClient
    {
        private readonly IApplicationClient _applicationClient;
        /// <summary>
        /// Creates client for controller. 
        /// </summary>
        /// <param name="httpClient">
        ///     HttpClient which will be used to call application.
        /// </param>
        /// <param name="serviceProvider">
        ///     Application serviceProvider.
        /// </param>
        public WeatherForecastControllerClient(HttpClient httpClient, IServiceProvider serviceProvider)
        {
            var applicationClientFactory = serviceProvider.GetService<IApplicationClientFactory>();
            if(applicationClientFactory == null)
            {
                throw new InvalidOperationException("'IApplicationClientFactory' could not be resolved. Did you forget to call WithRidge()?.");
            }
            else
            {
                _applicationClient = applicationClientFactory.CreateClient(serviceProvider, httpClient);
            }
        }
                /// <summary>
        ///     Calls <see cref="RidgeDemoWebApp.Controllers.WeatherForecastController.Get" />. 
        /// </summary> 
        public async Task<HttpCallResponse<System.Collections.Generic.IEnumerable<RidgeDemoWebApp.WeatherForecast>>> Get(params AdditionalParameter[] additionalParameters)
        {
            var methodName = nameof(RidgeDemoWebApp.Controllers.WeatherForecastController.Get);
            var actionParameters = new Type[] {
            };
            var parametersAndTransformations = new List<RawParameterAndTransformationInfo>()
            { 
            };
           return await _applicationClient.CallAction<System.Collections.Generic.IEnumerable<RidgeDemoWebApp.WeatherForecast>,RidgeDemoWebApp.Controllers.WeatherForecastController>(methodName, actionParameters, additionalParameters, parametersAndTransformations);
        }

 }
}
#pragma warning restore CS0419
#nullable restore

Code and pdf at

https://ignatandrei.github.io/RSCG_Examples/v2/docs/Ridge