first commit
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
using System.Data.Common;
|
||||
using Dotnet.Samples.AspNetCore.WebApi.Data;
|
||||
using Dotnet.Samples.AspNetCore.WebApi.Migrations;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
namespace Dotnet.Samples.AspNetCore.WebApi.Tests.Utilities
|
||||
{
|
||||
/// <summary>
|
||||
/// A Fake is a working implementation that's simpler than the real one.
|
||||
/// It usually has some "real" logic but is not suitable for production
|
||||
/// (e.g., an in‑memory database instead of a full SQL Server). Fakes are
|
||||
/// useful when you need behavior that's closer to reality but still want
|
||||
/// to avoid external dependencies.
|
||||
/// </summary>
|
||||
public static class DatabaseFakes
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates an in-memory SQLite connection and DbContext options for testing.
|
||||
/// The connection remains open for the lifetime of the test.
|
||||
/// </summary>
|
||||
/// <returns>A tuple containing the SQLite connection and DbContext options.</returns>
|
||||
public static (DbConnection, DbContextOptions<PlayerDbContext>) CreateSqliteConnection()
|
||||
{
|
||||
var dbConnection = new SqliteConnection("Filename=:memory:");
|
||||
dbConnection.Open();
|
||||
|
||||
var dbContextOptions = new DbContextOptionsBuilder<PlayerDbContext>()
|
||||
.UseSqlite(dbConnection)
|
||||
.ReplaceService<IMigrationsAssembly, ProviderSpecificMigrationsAssembly>()
|
||||
.Options;
|
||||
|
||||
return (dbConnection, dbContextOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a PlayerDbContext instance with the specified options.
|
||||
/// </summary>
|
||||
/// <param name="dbContextOptions">The DbContext options to use.</param>
|
||||
/// <returns>A new PlayerDbContext instance.</returns>
|
||||
public static PlayerDbContext CreateDbContext(
|
||||
DbContextOptions<PlayerDbContext> dbContextOptions
|
||||
)
|
||||
{
|
||||
return new PlayerDbContext(dbContextOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies all pending EF Core migrations to the test database, including seed data.
|
||||
/// Extension method for PlayerDbContext.
|
||||
/// </summary>
|
||||
/// <param name="context">The PlayerDbContext instance.</param>
|
||||
public static async Task MigrateAsync(this PlayerDbContext context)
|
||||
{
|
||||
await context.Database.MigrateAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
using Dotnet.Samples.AspNetCore.WebApi.Models;
|
||||
using Dotnet.Samples.AspNetCore.WebApi.Utilities;
|
||||
|
||||
namespace Dotnet.Samples.AspNetCore.WebApi.Tests.Utilities;
|
||||
|
||||
/// <summary>
|
||||
/// Test data factory for Player entities.
|
||||
/// Wraps production data from PlayerData with test-specific modifications (e.g., GUID assignment).
|
||||
/// A Fake is a working implementation that's simpler than the real one.
|
||||
/// It usually has some "real" logic but is not suitable for production
|
||||
/// (e.g., an in‑memory database instead of a full SQL Server). Fakes are
|
||||
/// useful when you need behavior that's closer to reality but still want
|
||||
/// to avoid external dependencies.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Data-state vocabulary used across controller tests:
|
||||
/// <list type="bullet">
|
||||
/// <item><term>existing</term><description>Player is present in the database.</description></item>
|
||||
/// <item><term>nonexistent</term><description>Player is absent, valid shape for creation (POST scenarios).</description></item>
|
||||
/// <item><term>unknown</term><description>Valid ID format, absent from database (404-by-lookup scenarios).</description></item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public static class PlayerFakes
|
||||
{
|
||||
private static string? FormatBirth(DateTime? dateOfBirth) =>
|
||||
dateOfBirth.HasValue ? $"{dateOfBirth.Value:MMMM d, yyyy}" : null;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the starting 11 players with generated GUIDs for in-memory testing.
|
||||
/// Reuses production player data from PlayerData.MakeStarting11().
|
||||
/// </summary>
|
||||
public static List<Player> MakeStarting11()
|
||||
{
|
||||
var players = PlayerData.MakeStarting11();
|
||||
|
||||
// Assign GUIDs for in-memory database testing
|
||||
foreach (var player in players)
|
||||
{
|
||||
player.Id = Guid.NewGuid();
|
||||
}
|
||||
|
||||
return players;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a specific player from the starting 11 by squad number.
|
||||
/// Reuses production player data from PlayerData.MakeStarting11().
|
||||
/// </summary>
|
||||
public static Player MakeFromStarting11(int squadNumber)
|
||||
{
|
||||
var player =
|
||||
PlayerData.MakeStarting11().SingleOrDefault(p => p.SquadNumber == squadNumber)
|
||||
?? throw new ArgumentNullException(
|
||||
$"Player with Squad Number {squadNumber} not found."
|
||||
);
|
||||
|
||||
player.Id = Guid.NewGuid();
|
||||
return player;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a new player (substitute) for testing create operations.
|
||||
/// Reuses production player data from PlayerData.GetSubstitutes().
|
||||
/// </summary>
|
||||
public static Player MakeNew()
|
||||
{
|
||||
// Get Giovani Lo Celso (squad number 27) from substitutes
|
||||
var player =
|
||||
PlayerData.GetSubstitutes().SingleOrDefault(player => player.SquadNumber == 27)
|
||||
?? throw new InvalidOperationException(
|
||||
"Substitute player with squad number 27 not found."
|
||||
);
|
||||
|
||||
player.Id = Guid.NewGuid();
|
||||
return player;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------
|
||||
* Create
|
||||
* ---------------------------------------------------------------------- */
|
||||
|
||||
/// <summary>
|
||||
/// Creates a PlayerRequestModel for testing create operations.
|
||||
/// Uses data from a substitute player (Giovani Lo Celso).
|
||||
/// </summary>
|
||||
public static PlayerRequestModel MakeRequestModelForCreate()
|
||||
{
|
||||
var player = MakeNew();
|
||||
|
||||
return new PlayerRequestModel()
|
||||
{
|
||||
FirstName = player.FirstName,
|
||||
MiddleName = player.MiddleName,
|
||||
LastName = player.LastName,
|
||||
DateOfBirth = player.DateOfBirth,
|
||||
SquadNumber = player.SquadNumber,
|
||||
AbbrPosition = player.AbbrPosition,
|
||||
Team = player.Team,
|
||||
League = player.League,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a PlayerResponseModel for testing create operation responses.
|
||||
/// Uses data from a substitute player (Giovani Lo Celso).
|
||||
/// </summary>
|
||||
public static PlayerResponseModel MakeResponseModelForCreate()
|
||||
{
|
||||
var player = MakeNew();
|
||||
|
||||
return new PlayerResponseModel
|
||||
{
|
||||
FullName =
|
||||
$"{player.FirstName} {(string.IsNullOrWhiteSpace(player.MiddleName) ? "" : player.MiddleName + " ")}{player.LastName}".Trim(),
|
||||
Birth = FormatBirth(player.DateOfBirth),
|
||||
Dorsal = player.SquadNumber,
|
||||
Position = player.Position,
|
||||
Club = player.Team,
|
||||
League = player.League,
|
||||
Starting11 = player.Starting11 ? "Yes" : "No",
|
||||
};
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------
|
||||
* Retrieve
|
||||
* ---------------------------------------------------------------------- */
|
||||
|
||||
/// <summary>
|
||||
/// Creates a PlayerRequestModel for testing retrieve operations.
|
||||
/// Uses data from the starting 11 based on the specified squad number.
|
||||
/// </summary>
|
||||
/// <param name="squadNumber">The squad number of the player to retrieve.</param>
|
||||
public static PlayerRequestModel MakeRequestModelForRetrieve(int squadNumber)
|
||||
{
|
||||
var player =
|
||||
PlayerData.MakeStarting11().SingleOrDefault(p => p.SquadNumber == squadNumber)
|
||||
?? throw new ArgumentNullException(
|
||||
$"Player with Squad Number {squadNumber} not found."
|
||||
);
|
||||
|
||||
return new PlayerRequestModel
|
||||
{
|
||||
FirstName = player.FirstName,
|
||||
MiddleName = player.MiddleName,
|
||||
LastName = player.LastName,
|
||||
DateOfBirth = player.DateOfBirth,
|
||||
SquadNumber = player.SquadNumber,
|
||||
AbbrPosition = player.AbbrPosition,
|
||||
Team = player.Team,
|
||||
League = player.League,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a PlayerResponseModel for testing retrieve operation responses.
|
||||
/// Uses data from the starting 11 based on the specified squad number.
|
||||
/// </summary>
|
||||
/// <param name="squadNumber">The squad number of the player to retrieve.</param>
|
||||
public static PlayerResponseModel MakeResponseModelForRetrieve(int squadNumber)
|
||||
{
|
||||
var player =
|
||||
PlayerData.MakeStarting11().SingleOrDefault(p => p.SquadNumber == squadNumber)
|
||||
?? throw new ArgumentNullException(
|
||||
$"Player with Squad Number {squadNumber} not found."
|
||||
);
|
||||
|
||||
return new PlayerResponseModel
|
||||
{
|
||||
FullName =
|
||||
$"{player.FirstName} {(string.IsNullOrWhiteSpace(player.MiddleName) ? "" : player.MiddleName + " ")}{player.LastName}".Trim(),
|
||||
Birth = FormatBirth(player.DateOfBirth),
|
||||
Dorsal = player.SquadNumber,
|
||||
Position = player.Position,
|
||||
Club = player.Team,
|
||||
League = player.League,
|
||||
Starting11 = player.Starting11 ? "Yes" : "No",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of PlayerResponseModel for testing retrieve all operations.
|
||||
/// Uses all players from the starting 11.
|
||||
/// </summary>
|
||||
public static List<PlayerResponseModel> MakeResponseModelsForRetrieve() =>
|
||||
[
|
||||
.. PlayerData
|
||||
.MakeStarting11()
|
||||
.Select(player =>
|
||||
{
|
||||
player.Id = Guid.NewGuid();
|
||||
return new PlayerResponseModel
|
||||
{
|
||||
FullName =
|
||||
$"{player.FirstName} {(string.IsNullOrWhiteSpace(player.MiddleName) ? "" : player.MiddleName + " ")}{player.LastName}".Trim(),
|
||||
Birth = FormatBirth(player.DateOfBirth),
|
||||
Dorsal = player.SquadNumber,
|
||||
Position = player.Position,
|
||||
Club = player.Team,
|
||||
League = player.League,
|
||||
Starting11 = player.Starting11 ? "Yes" : "No",
|
||||
};
|
||||
}),
|
||||
];
|
||||
|
||||
/* -------------------------------------------------------------------------
|
||||
* Update
|
||||
* ---------------------------------------------------------------------- */
|
||||
|
||||
/// <summary>
|
||||
/// Creates a PlayerRequestModel for testing update operations.
|
||||
/// Delegates to MakeRequestModelForRetrieve.
|
||||
/// </summary>
|
||||
/// <param name="squadNumber">The squad number of the player to update.</param>
|
||||
public static PlayerRequestModel MakeRequestModelForUpdate(int squadNumber)
|
||||
{
|
||||
return MakeRequestModelForRetrieve(squadNumber);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a PlayerResponseModel for testing update operation responses.
|
||||
/// Delegates to MakeResponseModelForRetrieve.
|
||||
/// </summary>
|
||||
/// <param name="squadNumber">The squad number of the player to update.</param>
|
||||
public static PlayerResponseModel MakeResponseModelForUpdate(int squadNumber)
|
||||
{
|
||||
return MakeResponseModelForRetrieve(squadNumber);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using AutoMapper;
|
||||
using Dotnet.Samples.AspNetCore.WebApi.Controllers;
|
||||
using Dotnet.Samples.AspNetCore.WebApi.Models;
|
||||
using Dotnet.Samples.AspNetCore.WebApi.Repositories;
|
||||
using Dotnet.Samples.AspNetCore.WebApi.Services;
|
||||
using FluentValidation;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Routing;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
|
||||
namespace Dotnet.Samples.AspNetCore.WebApi.Tests.Utilities
|
||||
{
|
||||
/// <summary>
|
||||
/// A Mock is a dynamic test double that not only provides responses but
|
||||
/// also records interactions. Mocks are pre‑programmed with expectations
|
||||
/// (like “this method should be called once with these parameters”) and can
|
||||
/// later verify that the expected calls occurred. Frameworks such as Moq
|
||||
/// make it easy to set up and verify these interactions.
|
||||
/// </summary>
|
||||
public static class PlayerMocks
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes mocks for PlayerController dependencies.
|
||||
/// </summary>
|
||||
/// <returns>A tuple containing mocked service, logger, and validator.</returns>
|
||||
public static (
|
||||
Mock<IPlayerService> service,
|
||||
Mock<ILogger<PlayerController>> logger,
|
||||
Mock<IValidator<PlayerRequestModel>> validator
|
||||
) InitControllerMocks()
|
||||
{
|
||||
var service = new Mock<IPlayerService>();
|
||||
var logger = new Mock<ILogger<PlayerController>>();
|
||||
var validator = new Mock<IValidator<PlayerRequestModel>>();
|
||||
|
||||
return (service, logger, validator);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mock IUrlHelper configured to return any string for Action calls.
|
||||
/// </summary>
|
||||
/// <returns>A configured Mock of IUrlHelper.</returns>
|
||||
public static Mock<IUrlHelper> SetupUrlHelperMock()
|
||||
{
|
||||
var mock = new Mock<IUrlHelper>();
|
||||
mock.Setup(url => url.Action(It.IsAny<UrlActionContext>())).Returns(It.IsAny<string>());
|
||||
|
||||
return mock;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes mocks for PlayerService dependencies.
|
||||
/// </summary>
|
||||
/// <param name="cacheValue">Optional cache value to return from memory cache.</param>
|
||||
/// <param name="environmentName">The environment name (defaults to "Development").</param>
|
||||
/// <returns>A tuple containing mocked repository, logger, cache, mapper, and environment.</returns>
|
||||
public static (
|
||||
Mock<IPlayerRepository> repository,
|
||||
Mock<ILogger<PlayerService>> logger,
|
||||
Mock<IMemoryCache> memoryCache,
|
||||
Mock<IMapper> mapper,
|
||||
Mock<IHostEnvironment> environment
|
||||
) InitServiceMocks(object? cacheValue = null, string environmentName = "Development")
|
||||
{
|
||||
var repository = new Mock<IPlayerRepository>();
|
||||
var logger = new Mock<ILogger<PlayerService>>();
|
||||
var memoryCache = SetupMemoryCacheMock(cacheValue ?? It.IsAny<object>());
|
||||
var mapper = new Mock<IMapper>();
|
||||
var environment = new Mock<IHostEnvironment>();
|
||||
environment.Setup(env => env.EnvironmentName).Returns(environmentName);
|
||||
return (repository, logger, memoryCache, mapper, environment);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mock IMemoryCache with configurable behavior.
|
||||
/// First TryGetValue call returns false, subsequent calls return true with the specified value.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to return from cache after the first call.</param>
|
||||
/// <returns>A configured Mock of IMemoryCache.</returns>
|
||||
public static Mock<IMemoryCache> SetupMemoryCacheMock(object? value)
|
||||
{
|
||||
var cachedValue = false;
|
||||
var mock = new Mock<IMemoryCache>();
|
||||
|
||||
mock.Setup(cache => cache.TryGetValue(It.IsAny<object>(), out It.Ref<object>.IsAny!))
|
||||
.Callback(
|
||||
new TryGetValueDelegate(
|
||||
(object _, out object? output) =>
|
||||
{
|
||||
output = cachedValue ? value : null;
|
||||
}
|
||||
)
|
||||
)
|
||||
.Returns(() =>
|
||||
{
|
||||
bool hasValue = cachedValue;
|
||||
cachedValue = true; // Subsequent invocations will return true
|
||||
return hasValue;
|
||||
});
|
||||
|
||||
mock.Setup(cache => cache.CreateEntry(It.IsAny<object>()))
|
||||
.Returns(Mock.Of<ICacheEntry>);
|
||||
mock.Setup(cache => cache.Remove(It.IsAny<object>()));
|
||||
|
||||
return mock;
|
||||
}
|
||||
|
||||
private delegate void TryGetValueDelegate(object key, out object? value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.Data.Common;
|
||||
using Dotnet.Samples.AspNetCore.WebApi.Data;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Dotnet.Samples.AspNetCore.WebApi.Tests.Utilities
|
||||
{
|
||||
/// <summary>
|
||||
/// A Stub provides pre‑configured, hard‑coded responses to method calls.
|
||||
/// Its purpose is simply to supply data to the system under test without
|
||||
/// any behavior verification. For example, a Stub for a repository might
|
||||
/// always return a specific user regardless of the input.
|
||||
/// </summary>
|
||||
public static class PlayerStubs
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a ModelStateDictionary with a single validation error.
|
||||
/// Used for testing validation failure scenarios.
|
||||
/// </summary>
|
||||
/// <param name="key">The property name or key for the error.</param>
|
||||
/// <param name="errorMessage">The error message.</param>
|
||||
/// <returns>A ModelStateDictionary containing the specified error.</returns>
|
||||
public static ModelStateDictionary CreateModelError(string key, string errorMessage)
|
||||
{
|
||||
var modelStateDictionary = new ModelStateDictionary();
|
||||
modelStateDictionary.AddModelError(key, errorMessage);
|
||||
return modelStateDictionary;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Dotnet.Samples.AspNetCore.WebApi.Tests.Utilities;
|
||||
|
||||
/// <summary>
|
||||
/// A test authentication handler that automatically authenticates every request,
|
||||
/// bypassing the real authentication scheme. Used in integration tests to exercise
|
||||
/// endpoints protected with [Authorize] without requiring a real token.
|
||||
/// </summary>
|
||||
internal sealed class TestAuthHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder
|
||||
) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
public const string SchemeName = "Test";
|
||||
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var claims = new[] { new Claim(ClaimTypes.Name, "TestUser") };
|
||||
var identity = new ClaimsIdentity(claims, SchemeName);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
var ticket = new AuthenticationTicket(principal, SchemeName);
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user