using Barcode.Host.Shared.DataModels; using Barcode.Host.Shared.Models.Stateless; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Barcode.Host.Tests; [TestClass] public class UnitTestLastScanController { private static ILogger? _Logger; private static string? _ControllerName; private static TestContext? _TestContext; private static WebApplicationFactory? _WebApplicationFactory; [ClassInitialize] public static void ClassInitAsync(TestContext testContext) { _TestContext = testContext; _WebApplicationFactory = new WebApplicationFactory(); IServiceProvider serviceProvider = _WebApplicationFactory.Services.CreateScope().ServiceProvider; _Logger = serviceProvider.GetRequiredService>(); _ControllerName = nameof(Server.ApiControllers.LastScanController)[..^10]; } private static void NonThrowTryCatch() { try { throw new Exception(); } catch (Exception) { } } [TestMethod] public void TestControllerName() { _Logger?.LogInformation("Starting Web Application"); Assert.AreEqual(ILastScanController.GetRouteName(), _ControllerName); _Logger?.LogInformation("{testName} completed", _TestContext?.TestName); NonThrowTryCatch(); } #if DEBUG [Ignore] #endif [TestMethod] public void GetScan() { _Logger?.LogInformation("Starting Web Application"); IServiceProvider? serviceProvider = _WebApplicationFactory?.Services.CreateScope().ServiceProvider; ILastScanService? lastScanService = serviceProvider?.GetRequiredService(); Assert.IsNotNull(lastScanService); Result result = lastScanService.GetScan(); Assert.IsNotNull(result?.Results); _Logger?.LogInformation("{testName} completed", _TestContext?.TestName); NonThrowTryCatch(); } #if DEBUG [Ignore] #endif [TestMethod] public async Task GetScanApi() { HttpClient? httpClient = _WebApplicationFactory?.CreateClient(); _Logger?.LogInformation("Starting Web Application"); Assert.IsNotNull(httpClient); string? json = await httpClient.GetStringAsync($"api/{_ControllerName}/O171927.1.37/"); File.WriteAllText(Path.Combine(AppContext.BaseDirectory, $"{_ControllerName}-{nameof(GetScan)}.json"), json); Result? result = System.Text.Json.JsonSerializer.Deserialize>(json); Assert.IsNotNull(result?.Results); _Logger?.LogInformation("{testName} completed", _TestContext?.TestName); NonThrowTryCatch(); } }