diff --git a/README.md b/README.md
index 09cb0da..f4fc306 100644
--- a/README.md
+++ b/README.md
@@ -73,7 +73,7 @@ The one deliberate break from Clean Architecture is that the Presentation projec
### Project structure
-1. **Presentation** - Exposes the Application layer to AI clients as an MCP server over HTTP. Tools are grouped by feature, validate their input and hand the work to MediatR.
+1. **Presentation** - Exposes the Application layer to AI clients as an MCP server over HTTP. Tools are grouped by feature, send commands and queries through Mediator, and turn Application errors into MCP tool errors.
1. **Application** - Owns the domain and business logic. Commands and queries are validated and handled here, and each domain type has its own repository interface. This layer doesn't care what fulfils those contracts, as long as something does.
1. **Infrastructure** - Owns the data. It implements the repository interfaces to fetch, create, update and remove data, and maps its own data models onto the Application entities so persistence details don't leak upwards.
@@ -81,8 +81,9 @@ The one deliberate break from Clean Architecture is that the Presentation projec
- MCP server using the [MCP C# SDK](https://github.com/modelcontextprotocol/csharp-sdk)
- Logging using [Serilog](https://github.com/serilog/serilog), with [Seq](https://datalust.co/seq) when running in Docker
-- Mediator pattern using [MediatR](https://github.com/jbogard/MediatR)
-- Validation using [FluentValidation](https://github.com/FluentValidation/FluentValidation)
+- Mediator pattern using [Mediator](https://github.com/martinothamar/Mediator)
+- Validation using [FluentValidation](https://github.com/FluentValidation/FluentValidation) in an Application pipeline behaviour
+- Tool errors mapped from Application exceptions by a single call-tool filter
- Object mapping using [Mapperly](https://mapperly.riok.app)
- In-memory data using [Entity Framework Core](https://learn.microsoft.com/ef/core/providers/in-memory/) seeded with [Bogus](https://github.com/bchavez/Bogus)
- Testing using [xUnit](https://xunit.net), [Shouldly](https://github.com/shouldly/shouldly) and [NSubstitute](https://github.com/nsubstitute/NSubstitute), with coverage from [Coverlet](https://github.com/coverlet-coverage/coverlet)
diff --git a/src/Application/Application.csproj b/src/Application/Application.csproj
index 681da40..df905de 100644
--- a/src/Application/Application.csproj
+++ b/src/Application/Application.csproj
@@ -5,7 +5,8 @@
-
+
+
diff --git a/src/Application/Authors/Queries/GetAuthorById/GetAuthorByIdHandler.cs b/src/Application/Authors/Queries/GetAuthorById/GetAuthorByIdHandler.cs
index 62bfea4..d837845 100644
--- a/src/Application/Authors/Queries/GetAuthorById/GetAuthorByIdHandler.cs
+++ b/src/Application/Authors/Queries/GetAuthorById/GetAuthorByIdHandler.cs
@@ -5,11 +5,11 @@ namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthorById;
using Common.Enums;
using Common.Exceptions;
using Entities;
-using MediatR;
+using Mediator;
public class GetAuthorByIdHandler(IAuthorsRepository repository) : IRequestHandler
{
- public async Task Handle(GetAuthorByIdQuery request, CancellationToken cancellationToken)
+ public async ValueTask Handle(GetAuthorByIdQuery request, CancellationToken cancellationToken)
{
var result = await repository.GetAuthorById(request.Id, cancellationToken);
diff --git a/src/Application/Authors/Queries/GetAuthorById/GetAuthorByIdQuery.cs b/src/Application/Authors/Queries/GetAuthorById/GetAuthorByIdQuery.cs
index fd3e6fe..e4d9b6c 100644
--- a/src/Application/Authors/Queries/GetAuthorById/GetAuthorByIdQuery.cs
+++ b/src/Application/Authors/Queries/GetAuthorById/GetAuthorByIdQuery.cs
@@ -2,7 +2,7 @@ namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthorById;
using System.ComponentModel.DataAnnotations;
using Entities;
-using MediatR;
+using Mediator;
public class GetAuthorByIdQuery : IRequest
{
diff --git a/src/Application/Authors/Queries/GetAuthorById/GetAuthorByIdValidator.cs b/src/Application/Authors/Queries/GetAuthorById/GetAuthorByIdValidator.cs
new file mode 100644
index 0000000..da269c3
--- /dev/null
+++ b/src/Application/Authors/Queries/GetAuthorById/GetAuthorByIdValidator.cs
@@ -0,0 +1,11 @@
+namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthorById;
+
+using FluentValidation;
+
+public class GetAuthorByIdValidator : AbstractValidator
+{
+ public GetAuthorByIdValidator()
+ {
+ _ = this.RuleFor(r => r.Id).NotNull().NotEqual(Guid.Empty).WithMessage("An Author Id was not supplied.");
+ }
+}
diff --git a/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs b/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs
index 0bce59d..00af4f7 100644
--- a/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs
+++ b/src/Application/Authors/Queries/GetAuthors/GetAuthorsHandler.cs
@@ -3,11 +3,11 @@ namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors;
using System.Threading;
using System.Threading.Tasks;
using Entities;
-using MediatR;
+using Mediator;
public class GetAuthorsHandler(IAuthorsRepository repository) : IRequestHandler>
{
- public async Task> Handle(GetAuthorsQuery request, CancellationToken cancellationToken)
+ public async ValueTask> Handle(GetAuthorsQuery request, CancellationToken cancellationToken)
{
return await repository.GetAuthors(cancellationToken);
}
diff --git a/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs b/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs
index 11045de..fa23471 100644
--- a/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs
+++ b/src/Application/Authors/Queries/GetAuthors/GetAuthorsQuery.cs
@@ -1,7 +1,7 @@
namespace CleanModelContextProtocol.Application.Authors.Queries.GetAuthors;
using Entities;
-using MediatR;
+using Mediator;
public class GetAuthorsQuery : IRequest>
{
diff --git a/src/Application/Common/Behaviours/ValidationBehaviour.cs b/src/Application/Common/Behaviours/ValidationBehaviour.cs
new file mode 100644
index 0000000..152d716
--- /dev/null
+++ b/src/Application/Common/Behaviours/ValidationBehaviour.cs
@@ -0,0 +1,29 @@
+namespace CleanModelContextProtocol.Application.Common.Behaviours;
+
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using FluentValidation;
+using Mediator;
+
+public class ValidationBehaviour(IEnumerable> validators) : IPipelineBehavior
+ where TMessage : IMessage
+{
+ public async ValueTask Handle(TMessage message, MessageHandlerDelegate next, CancellationToken cancellationToken)
+ {
+ if (validators.Any())
+ {
+ var context = new ValidationContext(message);
+ var validationResults = await Task.WhenAll(validators.Select(v => v.ValidateAsync(context, cancellationToken)));
+ var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList();
+
+ if (failures.Count != 0)
+ {
+ throw new ValidationException(failures);
+ }
+ }
+
+ return await next(message, cancellationToken);
+ }
+}
diff --git a/src/Application/DependencyInjection.cs b/src/Application/DependencyInjection.cs
index 2c20c44..832b96d 100644
--- a/src/Application/DependencyInjection.cs
+++ b/src/Application/DependencyInjection.cs
@@ -2,7 +2,9 @@ namespace CleanModelContextProtocol.Application;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
-using MediatR;
+using Common.Behaviours;
+using FluentValidation;
+using Mediator;
using Microsoft.Extensions.DependencyInjection;
[ExcludeFromCodeCoverage]
@@ -10,7 +12,8 @@ public static class DependencyInjection
{
public static IServiceCollection AddApplication(this IServiceCollection services)
{
- _ = services.AddMediatR(Assembly.GetExecutingAssembly());
+ _ = services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Transient);
+ _ = services.AddScoped(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
return services;
}
diff --git a/src/Application/Movies/Queries/GetMovieById/GetMovieByIdHandler.cs b/src/Application/Movies/Queries/GetMovieById/GetMovieByIdHandler.cs
index 0aef59a..35b1043 100644
--- a/src/Application/Movies/Queries/GetMovieById/GetMovieByIdHandler.cs
+++ b/src/Application/Movies/Queries/GetMovieById/GetMovieByIdHandler.cs
@@ -5,11 +5,11 @@ namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovieById;
using Common.Enums;
using Common.Exceptions;
using Entities;
-using MediatR;
+using Mediator;
public class GetMovieByIdHandler(IMoviesRepository repository) : IRequestHandler
{
- public async Task Handle(GetMovieByIdQuery request, CancellationToken cancellationToken)
+ public async ValueTask Handle(GetMovieByIdQuery request, CancellationToken cancellationToken)
{
var result = await repository.GetMovieById(request.Id, cancellationToken);
diff --git a/src/Application/Movies/Queries/GetMovieById/GetMovieByIdQuery.cs b/src/Application/Movies/Queries/GetMovieById/GetMovieByIdQuery.cs
index 63296e3..e11049f 100644
--- a/src/Application/Movies/Queries/GetMovieById/GetMovieByIdQuery.cs
+++ b/src/Application/Movies/Queries/GetMovieById/GetMovieByIdQuery.cs
@@ -2,7 +2,7 @@ namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovieById;
using System.ComponentModel.DataAnnotations;
using Entities;
-using MediatR;
+using Mediator;
public class GetMovieByIdQuery : IRequest
{
diff --git a/src/Application/Movies/Queries/GetMovieById/GetMovieByIdValidator.cs b/src/Application/Movies/Queries/GetMovieById/GetMovieByIdValidator.cs
new file mode 100644
index 0000000..0d1b7cf
--- /dev/null
+++ b/src/Application/Movies/Queries/GetMovieById/GetMovieByIdValidator.cs
@@ -0,0 +1,11 @@
+namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovieById;
+
+using FluentValidation;
+
+public class GetMovieByIdValidator : AbstractValidator
+{
+ public GetMovieByIdValidator()
+ {
+ _ = this.RuleFor(r => r.Id).NotEqual(Guid.Empty).WithMessage("A Movie Id was not supplied.");
+ }
+}
diff --git a/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs b/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs
index 0aae83d..81488e2 100644
--- a/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs
+++ b/src/Application/Movies/Queries/GetMovies/GetMoviesHandler.cs
@@ -3,11 +3,11 @@ namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovies;
using System.Threading;
using System.Threading.Tasks;
using Entities;
-using MediatR;
+using Mediator;
public class GetMoviesHandler(IMoviesRepository repository) : IRequestHandler>
{
- public async Task> Handle(GetMoviesQuery request, CancellationToken cancellationToken)
+ public async ValueTask> Handle(GetMoviesQuery request, CancellationToken cancellationToken)
{
return await repository.GetMovies(cancellationToken);
}
diff --git a/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs b/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs
index 244a037..03a644c 100644
--- a/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs
+++ b/src/Application/Movies/Queries/GetMovies/GetMoviesQuery.cs
@@ -1,7 +1,7 @@
namespace CleanModelContextProtocol.Application.Movies.Queries.GetMovies;
using Entities;
-using MediatR;
+using Mediator;
public class GetMoviesQuery : IRequest>
{
diff --git a/src/Application/Reviews/Commands/CreateReview/CreateReviewCommand.cs b/src/Application/Reviews/Commands/CreateReview/CreateReviewCommand.cs
index 6f93b22..a889115 100644
--- a/src/Application/Reviews/Commands/CreateReview/CreateReviewCommand.cs
+++ b/src/Application/Reviews/Commands/CreateReview/CreateReviewCommand.cs
@@ -1,7 +1,7 @@
namespace CleanModelContextProtocol.Application.Reviews.Commands.CreateReview;
using Entities;
-using MediatR;
+using Mediator;
public class CreateReviewCommand : IRequest
{
diff --git a/src/Application/Reviews/Commands/CreateReview/CreateReviewHandler.cs b/src/Application/Reviews/Commands/CreateReview/CreateReviewHandler.cs
index 7103ef3..ff9378e 100644
--- a/src/Application/Reviews/Commands/CreateReview/CreateReviewHandler.cs
+++ b/src/Application/Reviews/Commands/CreateReview/CreateReviewHandler.cs
@@ -6,7 +6,7 @@ namespace CleanModelContextProtocol.Application.Reviews.Commands.CreateReview;
using Common.Enums;
using Common.Exceptions;
using Entities;
-using MediatR;
+using Mediator;
using Movies;
public class CreateReviewHandler(
@@ -14,7 +14,7 @@ public class CreateReviewHandler(
IMoviesRepository moviesRepository,
IReviewsRepository reviewsRepository) : IRequestHandler
{
- public async Task Handle(CreateReviewCommand request, CancellationToken cancellationToken)
+ public async ValueTask Handle(CreateReviewCommand request, CancellationToken cancellationToken)
{
if (!await authorsRepository.AuthorExists(request.AuthorId, cancellationToken))
{
diff --git a/src/Presentation/Validators/CreateReviewValidator.cs b/src/Application/Reviews/Commands/CreateReview/CreateReviewValidator.cs
similarity index 80%
rename from src/Presentation/Validators/CreateReviewValidator.cs
rename to src/Application/Reviews/Commands/CreateReview/CreateReviewValidator.cs
index 0b146d5..deb987b 100644
--- a/src/Presentation/Validators/CreateReviewValidator.cs
+++ b/src/Application/Reviews/Commands/CreateReview/CreateReviewValidator.cs
@@ -1,9 +1,8 @@
-namespace CleanModelContextProtocol.Presentation.Validators;
+namespace CleanModelContextProtocol.Application.Reviews.Commands.CreateReview;
-using CleanModelContextProtocol.Presentation.Requests;
using FluentValidation;
-public class CreateReviewValidator : AbstractValidator
+public class CreateReviewValidator : AbstractValidator
{
public CreateReviewValidator()
{
diff --git a/src/Application/Reviews/Commands/DeleteReview/DeleteReviewCommand.cs b/src/Application/Reviews/Commands/DeleteReview/DeleteReviewCommand.cs
index 0958bf1..404db65 100644
--- a/src/Application/Reviews/Commands/DeleteReview/DeleteReviewCommand.cs
+++ b/src/Application/Reviews/Commands/DeleteReview/DeleteReviewCommand.cs
@@ -1,6 +1,6 @@
namespace CleanModelContextProtocol.Application.Reviews.Commands.DeleteReview;
-using MediatR;
+using Mediator;
public class DeleteReviewCommand : IRequest
{
diff --git a/src/Application/Reviews/Commands/DeleteReview/DeleteReviewHandler.cs b/src/Application/Reviews/Commands/DeleteReview/DeleteReviewHandler.cs
index 5855c7b..088dacf 100644
--- a/src/Application/Reviews/Commands/DeleteReview/DeleteReviewHandler.cs
+++ b/src/Application/Reviews/Commands/DeleteReview/DeleteReviewHandler.cs
@@ -4,11 +4,11 @@ namespace CleanModelContextProtocol.Application.Reviews.Commands.DeleteReview;
using System.Threading.Tasks;
using Common.Enums;
using Common.Exceptions;
-using MediatR;
+using Mediator;
public class DeleteReviewHandler(IReviewsRepository repository) : IRequestHandler
{
- public async Task Handle(DeleteReviewCommand request, CancellationToken cancellationToken)
+ public async ValueTask Handle(DeleteReviewCommand request, CancellationToken cancellationToken)
{
if (!await repository.ReviewExists(request.Id, cancellationToken))
{
diff --git a/src/Application/Reviews/Commands/DeleteReview/DeleteReviewValidator.cs b/src/Application/Reviews/Commands/DeleteReview/DeleteReviewValidator.cs
new file mode 100644
index 0000000..0e339ab
--- /dev/null
+++ b/src/Application/Reviews/Commands/DeleteReview/DeleteReviewValidator.cs
@@ -0,0 +1,11 @@
+namespace CleanModelContextProtocol.Application.Reviews.Commands.DeleteReview;
+
+using FluentValidation;
+
+public class DeleteReviewValidator : AbstractValidator
+{
+ public DeleteReviewValidator()
+ {
+ _ = this.RuleFor(r => r.Id).NotEqual(Guid.Empty).WithMessage("A review Id was not supplied.");
+ }
+}
diff --git a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs
index 8b44f2b..0f11c5d 100644
--- a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs
+++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewCommand.cs
@@ -1,6 +1,6 @@
namespace CleanModelContextProtocol.Application.Reviews.Commands.UpdateReview;
-using MediatR;
+using Mediator;
public class UpdateReviewCommand : IRequest
{
diff --git a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs
index 20a8395..90b07f3 100644
--- a/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs
+++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewHandler.cs
@@ -6,14 +6,14 @@ namespace CleanModelContextProtocol.Application.Reviews.Commands.UpdateReview;
using CleanModelContextProtocol.Application.Movies;
using Common.Enums;
using Common.Exceptions;
-using MediatR;
+using Mediator;
public class UpdateReviewHandler(
IAuthorsRepository authorsRepository,
IMoviesRepository moviesRepository,
IReviewsRepository reviewsRepository) : IRequestHandler
{
- public async Task Handle(UpdateReviewCommand request, CancellationToken cancellationToken)
+ public async ValueTask Handle(UpdateReviewCommand request, CancellationToken cancellationToken)
{
if (!await reviewsRepository.ReviewExists(request.Id, cancellationToken))
{
diff --git a/src/Presentation/Validators/UpdateReviewValidator.cs b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs
similarity index 70%
rename from src/Presentation/Validators/UpdateReviewValidator.cs
rename to src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs
index 176a209..d95b20f 100644
--- a/src/Presentation/Validators/UpdateReviewValidator.cs
+++ b/src/Application/Reviews/Commands/UpdateReview/UpdateReviewValidator.cs
@@ -1,12 +1,12 @@
-namespace CleanModelContextProtocol.Presentation.Validators;
+namespace CleanModelContextProtocol.Application.Reviews.Commands.UpdateReview;
-using CleanModelContextProtocol.Presentation.Requests;
using FluentValidation;
-public class UpdateReviewValidator : AbstractValidator
+public class UpdateReviewValidator : AbstractValidator
{
public UpdateReviewValidator()
{
+ _ = this.RuleFor(r => r.Id).NotEqual(Guid.Empty).WithMessage("A review id was not supplied to Update the review.");
_ = this.RuleFor(r => r.AuthorId).NotEqual(Guid.Empty).WithMessage("An author id was not supplied to Update the review.");
_ = this.RuleFor(r => r.MovieId).NotEqual(Guid.Empty).WithMessage("A movie id was not supplied to Update the review.");
_ = this.RuleFor(r => r.Stars).InclusiveBetween(1, 5).WithMessage("A star rating must be between 1 and 5.");
diff --git a/src/Application/Reviews/Queries/GetReviewById/GetReviewByIdHandler.cs b/src/Application/Reviews/Queries/GetReviewById/GetReviewByIdHandler.cs
index 4a17a12..53f4489 100644
--- a/src/Application/Reviews/Queries/GetReviewById/GetReviewByIdHandler.cs
+++ b/src/Application/Reviews/Queries/GetReviewById/GetReviewByIdHandler.cs
@@ -5,11 +5,11 @@ namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewById;
using Common.Enums;
using Common.Exceptions;
using Entities;
-using MediatR;
+using Mediator;
public class GetReviewByIdHandler(IReviewsRepository repository) : IRequestHandler
{
- public async Task Handle(GetReviewByIdQuery request, CancellationToken cancellationToken)
+ public async ValueTask Handle(GetReviewByIdQuery request, CancellationToken cancellationToken)
{
var result = await repository.GetReviewById(request.Id, cancellationToken);
diff --git a/src/Application/Reviews/Queries/GetReviewById/GetReviewByIdQuery.cs b/src/Application/Reviews/Queries/GetReviewById/GetReviewByIdQuery.cs
index a5dfd4c..1c30362 100644
--- a/src/Application/Reviews/Queries/GetReviewById/GetReviewByIdQuery.cs
+++ b/src/Application/Reviews/Queries/GetReviewById/GetReviewByIdQuery.cs
@@ -1,7 +1,7 @@
namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewById;
using Entities;
-using MediatR;
+using Mediator;
public class GetReviewByIdQuery : IRequest
{
diff --git a/src/Application/Reviews/Queries/GetReviewById/GetReviewByIdValidator.cs b/src/Application/Reviews/Queries/GetReviewById/GetReviewByIdValidator.cs
new file mode 100644
index 0000000..d6dcfd7
--- /dev/null
+++ b/src/Application/Reviews/Queries/GetReviewById/GetReviewByIdValidator.cs
@@ -0,0 +1,11 @@
+namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviewById;
+
+using FluentValidation;
+
+public class GetReviewByIdValidator : AbstractValidator
+{
+ public GetReviewByIdValidator()
+ {
+ _ = this.RuleFor(r => r.Id).NotNull().NotEqual(Guid.Empty).WithMessage("A Review Id was not supplied.");
+ }
+}
diff --git a/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs b/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs
index dbbace6..fc0c1a9 100644
--- a/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs
+++ b/src/Application/Reviews/Queries/GetReviews/GetReviewsHandler.cs
@@ -3,11 +3,11 @@ namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviews;
using System.Threading;
using System.Threading.Tasks;
using Entities;
-using MediatR;
+using Mediator;
public class GetReviewsHandler(IReviewsRepository repository) : IRequestHandler>
{
- public async Task> Handle(GetReviewsQuery request, CancellationToken cancellationToken)
+ public async ValueTask> Handle(GetReviewsQuery request, CancellationToken cancellationToken)
{
return await repository.GetReviews(cancellationToken);
}
diff --git a/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs b/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs
index cc617cc..23c80bc 100644
--- a/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs
+++ b/src/Application/Reviews/Queries/GetReviews/GetReviewsQuery.cs
@@ -1,7 +1,7 @@
namespace CleanModelContextProtocol.Application.Reviews.Queries.GetReviews;
using Entities;
-using MediatR;
+using Mediator;
public class GetReviewsQuery : IRequest>
{
diff --git a/src/Application/Versions/Queries/GetVersion/GetVersionHandler.cs b/src/Application/Versions/Queries/GetVersion/GetVersionHandler.cs
index 28f1208..fb698f5 100644
--- a/src/Application/Versions/Queries/GetVersion/GetVersionHandler.cs
+++ b/src/Application/Versions/Queries/GetVersion/GetVersionHandler.cs
@@ -4,11 +4,11 @@ namespace CleanModelContextProtocol.Application.Versions.Queries.GetVersion;
using System.Threading;
using System.Threading.Tasks;
using Entities;
-using MediatR;
+using Mediator;
public class GetVersionHandler : IRequestHandler
{
- public Task Handle(GetVersionQuery request, CancellationToken cancellationToken)
+ public ValueTask Handle(GetVersionQuery request, CancellationToken cancellationToken)
{
var assembly = Assembly.GetEntryAssembly();
@@ -20,6 +20,6 @@ public Task Handle(GetVersionQuery request, CancellationToken cancellat
$"{assembly?.GetCustomAttribute()?.InformationalVersion}"
};
- return Task.FromResult(version);
+ return ValueTask.FromResult(version);
}
}
diff --git a/src/Application/Versions/Queries/GetVersion/GetVersionQuery.cs b/src/Application/Versions/Queries/GetVersion/GetVersionQuery.cs
index d865021..a53461a 100644
--- a/src/Application/Versions/Queries/GetVersion/GetVersionQuery.cs
+++ b/src/Application/Versions/Queries/GetVersion/GetVersionQuery.cs
@@ -1,7 +1,7 @@
namespace CleanModelContextProtocol.Application.Versions.Queries.GetVersion;
using Entities;
-using MediatR;
+using Mediator;
public class GetVersionQuery : IRequest
{
diff --git a/src/Presentation/Errors/ToolErrorFilter.cs b/src/Presentation/Errors/ToolErrorFilter.cs
new file mode 100644
index 0000000..c46e932
--- /dev/null
+++ b/src/Presentation/Errors/ToolErrorFilter.cs
@@ -0,0 +1,45 @@
+namespace CleanModelContextProtocol.Presentation.Errors;
+
+using CleanModelContextProtocol.Application.Common.Exceptions;
+using FluentValidation;
+using ModelContextProtocol.Protocol;
+using ModelContextProtocol.Server;
+
+///
+/// Maps exceptions raised by the Application layer to MCP tool error results.
+///
+public static class ToolErrorFilter
+{
+ public static McpRequestHandler Filter(McpRequestHandler next)
+ {
+ return async (request, cancellationToken) =>
+ {
+ try
+ {
+ return await next(request, cancellationToken);
+ }
+ catch (Exception exception) when (exception is not OperationCanceledException)
+ {
+ return ToResult(exception);
+ }
+ };
+ }
+
+ public static CallToolResult ToResult(Exception exception)
+ {
+ var message = exception switch
+ {
+ ValidationException validationException => "Validation Failed: " + string.Join(" ", validationException.Errors
+ .Select(e => $"{e.PropertyName}: {e.ErrorMessage}")
+ .Distinct()),
+ NotFoundException => $"Not Found: {exception.Message}",
+ _ => "Error: An error occurred while processing your request."
+ };
+
+ return new CallToolResult
+ {
+ IsError = true,
+ Content = [new TextContentBlock { Text = message }]
+ };
+ }
+}
diff --git a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
index d5f0b8a..28c0ee0 100644
--- a/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
+++ b/src/Presentation/Extensions/WebApplicationBuilderExtensions.cs
@@ -5,8 +5,8 @@ namespace CleanModelContextProtocol.Presentation.Extensions;
using System.Text.Json;
using System.Text.Json.Serialization;
using Application;
+using CleanModelContextProtocol.Presentation.Errors;
using CleanModelContextProtocol.Presentation.Serialization;
-using FluentValidation;
using Infrastructure;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Json;
@@ -46,14 +46,9 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat
#endregion Serialisation
- #region Validation
-
- _ = builder.Services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Singleton);
-
- #endregion Validation
-
#region Project Dependencies
+ _ = builder.Services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped);
_ = builder.Services.AddInfrastructure();
_ = builder.Services.AddApplication();
@@ -88,7 +83,8 @@ public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicat
"that data for better formatting.";
})
.WithHttpTransport()
- .WithToolsFromAssembly();
+ .WithToolsFromAssembly()
+ .WithRequestFilters(filters => filters.AddCallToolFilter(ToolErrorFilter.Filter));
#endregion Model Context Protocol
diff --git a/src/Presentation/Presentation.csproj b/src/Presentation/Presentation.csproj
index 9f202eb..0d63580 100644
--- a/src/Presentation/Presentation.csproj
+++ b/src/Presentation/Presentation.csproj
@@ -15,7 +15,10 @@
-
+
+ all
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+
diff --git a/src/Presentation/Requests/CreateReviewRequest.cs b/src/Presentation/Requests/CreateReviewRequest.cs
deleted file mode 100644
index 63696fb..0000000
--- a/src/Presentation/Requests/CreateReviewRequest.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-namespace CleanModelContextProtocol.Presentation.Requests;
-
-public class CreateReviewRequest
-{
- public Guid AuthorId { get; init; }
-
- public Guid MovieId { get; init; }
-
- public int Stars { get; init; }
-}
diff --git a/src/Presentation/Requests/UpdateReviewRequest.cs b/src/Presentation/Requests/UpdateReviewRequest.cs
deleted file mode 100644
index 2968e4c..0000000
--- a/src/Presentation/Requests/UpdateReviewRequest.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-namespace CleanModelContextProtocol.Presentation.Requests;
-
-public class UpdateReviewRequest
-{
- public Guid AuthorId { get; init; }
-
- public Guid MovieId { get; init; }
-
- public int Stars { get; init; }
-}
diff --git a/src/Presentation/Serialization/AppJsonSerializerContext.cs b/src/Presentation/Serialization/AppJsonSerializerContext.cs
index 686cc34..f7b82e0 100644
--- a/src/Presentation/Serialization/AppJsonSerializerContext.cs
+++ b/src/Presentation/Serialization/AppJsonSerializerContext.cs
@@ -5,7 +5,6 @@ namespace CleanModelContextProtocol.Presentation.Serialization;
using Application.Movies.Entities;
using Application.Reviews.Entities;
using Application.Versions.Entities;
-using Requests;
///
/// JSON serialization context for compile-time source generation.
@@ -27,8 +26,6 @@ namespace CleanModelContextProtocol.Presentation.Serialization;
[JsonSerializable(typeof(ReviewedMovie))]
[JsonSerializable(typeof(Version))]
[JsonSerializable(typeof(List))]
-[JsonSerializable(typeof(CreateReviewRequest))]
-[JsonSerializable(typeof(UpdateReviewRequest))]
public partial class AppJsonSerializerContext : JsonSerializerContext
{
}
diff --git a/src/Presentation/Tools/AuthorTools.cs b/src/Presentation/Tools/AuthorTools.cs
index 0de7d0b..26fd2bd 100644
--- a/src/Presentation/Tools/AuthorTools.cs
+++ b/src/Presentation/Tools/AuthorTools.cs
@@ -2,8 +2,7 @@ namespace CleanModelContextProtocol.Presentation.Tools;
using System.ComponentModel;
using System.Text.Json;
-using CleanModelContextProtocol.Application.Common.Exceptions;
-using MediatR;
+using Mediator;
using ModelContextProtocol.Server;
using Queries = Application.Authors.Queries;
@@ -14,36 +13,18 @@ public static class AuthorTools
[Description("Get all authors in the system")]
public static async Task GetAllAuthors(ISender sender)
{
- try
- {
- var result = await sender.Send(new Queries.GetAuthors.GetAuthorsQuery());
+ var result = await sender.Send(new Queries.GetAuthors.GetAuthorsQuery());
- return JsonSerializer.Serialize(result);
- }
- catch (Exception ex)
- {
- return $"Error: {ex.Message}";
- }
+ return JsonSerializer.Serialize(result);
}
[McpServerTool(Name = "GetAuthorById", ReadOnly = true)]
[Description("Get a specific author by their unique ID")]
public static async Task GetAuthorById(ISender sender, [Description("The GUID of the author")] Guid id)
{
- try
- {
- return JsonSerializer.Serialize(await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery
- {
- Id = id
- }));
- }
- catch (NotFoundException ex)
- {
- return $"Not Found: {ex.Message}";
- }
- catch (Exception ex)
+ return JsonSerializer.Serialize(await sender.Send(new Queries.GetAuthorById.GetAuthorByIdQuery
{
- return $"Error: {ex.Message}";
- }
+ Id = id
+ }));
}
}
diff --git a/src/Presentation/Tools/MovieTools.cs b/src/Presentation/Tools/MovieTools.cs
index 9d3eadf..30546e7 100644
--- a/src/Presentation/Tools/MovieTools.cs
+++ b/src/Presentation/Tools/MovieTools.cs
@@ -2,8 +2,7 @@ namespace CleanModelContextProtocol.Presentation.Tools;
using System.ComponentModel;
using System.Text.Json;
-using CleanModelContextProtocol.Application.Common.Exceptions;
-using MediatR;
+using Mediator;
using ModelContextProtocol.Server;
using Queries = Application.Movies.Queries;
@@ -14,36 +13,18 @@ public static class MovieTools
[Description("Get all movies in the system")]
public static async Task GetAllMovies(ISender sender)
{
- try
- {
- var result = await sender.Send(new Queries.GetMovies.GetMoviesQuery());
+ var result = await sender.Send(new Queries.GetMovies.GetMoviesQuery());
- return JsonSerializer.Serialize(result);
- }
- catch (Exception ex)
- {
- return $"Error: {ex.Message}";
- }
+ return JsonSerializer.Serialize(result);
}
[McpServerTool(Name = "GetMovieById", ReadOnly = true)]
[Description("Get a specific movie by its unique ID")]
public static async Task GetMovieById(ISender sender, [Description("The GUID of the movie")] Guid id)
{
- try
- {
- return JsonSerializer.Serialize(await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery
- {
- Id = id
- }));
- }
- catch (NotFoundException ex)
- {
- return $"Not Found: {ex.Message}";
- }
- catch (Exception ex)
+ return JsonSerializer.Serialize(await sender.Send(new Queries.GetMovieById.GetMovieByIdQuery
{
- return $"Error: {ex.Message}";
- }
+ Id = id
+ }));
}
}
diff --git a/src/Presentation/Tools/ReviewTools.cs b/src/Presentation/Tools/ReviewTools.cs
index 8c971ab..14470f4 100644
--- a/src/Presentation/Tools/ReviewTools.cs
+++ b/src/Presentation/Tools/ReviewTools.cs
@@ -2,8 +2,7 @@ namespace CleanModelContextProtocol.Presentation.Tools;
using System.ComponentModel;
using System.Text.Json;
-using CleanModelContextProtocol.Application.Common.Exceptions;
-using MediatR;
+using Mediator;
using ModelContextProtocol.Server;
using Commands = Application.Reviews.Commands;
using Queries = Application.Reviews.Queries;
@@ -15,16 +14,9 @@ public static class ReviewTools
[Description("Get all reviews in the system")]
public static async Task GetAllReviews(ISender sender)
{
- try
- {
- var result = await sender.Send(new Queries.GetReviews.GetReviewsQuery());
+ var result = await sender.Send(new Queries.GetReviews.GetReviewsQuery());
- return JsonSerializer.Serialize(result);
- }
- catch (Exception ex)
- {
- return $"Error: {ex.Message}";
- }
+ return JsonSerializer.Serialize(result);
}
[McpServerTool(Name = "GetReviewById", ReadOnly = true)]
@@ -32,21 +24,10 @@ public static async Task GetAllReviews(ISender sender)
[Description("Get a specific review by its unique ID")]
public static async Task GetReviewById(ISender sender, [Description("The GUID of the review")] Guid id)
{
- try
- {
- return JsonSerializer.Serialize(await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery
- {
- Id = id
- }));
- }
- catch (NotFoundException ex)
+ return JsonSerializer.Serialize(await sender.Send(new Queries.GetReviewById.GetReviewByIdQuery
{
- return $"Not Found: {ex.Message}";
- }
- catch (Exception ex)
- {
- return $"Error: {ex.Message}";
- }
+ Id = id
+ }));
}
[McpServerTool(Name = "CreateReview")]
@@ -57,25 +38,14 @@ public static async Task CreateReview(
[Description("The GUID of the movie being reviewed")] Guid movieId,
[Description("Star rating for the movie (e.g. 1-5)")] int stars)
{
- try
+ var result = await sender.Send(new Commands.CreateReview.CreateReviewCommand
{
- var result = await sender.Send(new Commands.CreateReview.CreateReviewCommand
- {
- AuthorId = authorId,
- MovieId = movieId,
- Stars = stars
- });
+ AuthorId = authorId,
+ MovieId = movieId,
+ Stars = stars
+ });
- return JsonSerializer.Serialize(result);
- }
- catch (NotFoundException ex)
- {
- return $"Not Found: {ex.Message}";
- }
- catch (Exception ex)
- {
- return $"Error: {ex.Message}";
- }
+ return JsonSerializer.Serialize(result);
}
[McpServerTool(Name = "UpdateReview")]
@@ -87,48 +57,26 @@ public static async Task UpdateReview(
[Description("The GUID of the movie being reviewed")] Guid movieId,
[Description("Star rating for the movie (e.g. 1-5)")] int stars)
{
- try
+ _ = await sender.Send(new Commands.UpdateReview.UpdateReviewCommand
{
- _ = await sender.Send(new Commands.UpdateReview.UpdateReviewCommand
- {
- Id = id,
- AuthorId = authorId,
- MovieId = movieId,
- Stars = stars
- });
+ Id = id,
+ AuthorId = authorId,
+ MovieId = movieId,
+ Stars = stars
+ });
- return "Review updated successfully";
- }
- catch (NotFoundException ex)
- {
- return $"Not Found: {ex.Message}";
- }
- catch (Exception ex)
- {
- return $"Error: {ex.Message}";
- }
+ return "Review updated successfully";
}
[McpServerTool(Name = "DeleteReview")]
[Description("Delete a review by its unique ID")]
public static async Task DeleteReview(ISender sender, [Description("The GUID of the review to delete")] Guid id)
{
- try
+ _ = await sender.Send(new Commands.DeleteReview.DeleteReviewCommand
{
- _ = await sender.Send(new Commands.DeleteReview.DeleteReviewCommand
- {
- Id = id
- });
+ Id = id
+ });
- return "Review deleted successfully";
- }
- catch (NotFoundException ex)
- {
- return $"Not Found: {ex.Message}";
- }
- catch (Exception ex)
- {
- return $"Error: {ex.Message}";
- }
+ return "Review deleted successfully";
}
}
diff --git a/src/Presentation/Tools/VersionTools.cs b/src/Presentation/Tools/VersionTools.cs
index 100f053..1e86066 100644
--- a/src/Presentation/Tools/VersionTools.cs
+++ b/src/Presentation/Tools/VersionTools.cs
@@ -1,7 +1,7 @@
namespace CleanModelContextProtocol.Presentation.Tools;
using System.ComponentModel;
-using MediatR;
+using Mediator;
using ModelContextProtocol.Server;
using Queries = Application.Versions.Queries;
@@ -12,20 +12,13 @@ public static class VersionTools
[Description("Get the current application version details")]
public static async Task GetVersion(ISender sender)
{
- try
- {
- var result = await sender.Send(new Queries.GetVersion.GetVersionQuery());
+ var result = await sender.Send(new Queries.GetVersion.GetVersionQuery());
- return $"""
- | Property | Value |
- | --- | --- |
- | File Version | {result.FileVersion} |
- | Informational Version | {result.InformationalVersion} |
- """;
- }
- catch (Exception ex)
- {
- return $"Error: {ex.Message}";
- }
+ return $"""
+ | Property | Value |
+ | --- | --- |
+ | File Version | {result.FileVersion} |
+ | Informational Version | {result.InformationalVersion} |
+ """;
}
}
diff --git a/src/Presentation/Validators/GenericIdentityValidator.cs b/src/Presentation/Validators/GenericIdentityValidator.cs
deleted file mode 100644
index 5e8be88..0000000
--- a/src/Presentation/Validators/GenericIdentityValidator.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-namespace CleanModelContextProtocol.Presentation.Validators;
-
-using FluentValidation;
-
-public class GenericIdentityValidator : AbstractValidator
-{
- public GenericIdentityValidator()
- {
- _ = this.RuleFor(r => r)
- .NotNull()
- .NotEqual(Guid.Empty)
- .WithMessage("The Id supplied in the request is not valid.");
- }
-}
diff --git a/tests/Application.Tests.Unit/Authors/Queries/GetAuthorById/GetAuthorByIdValidatorTests.cs b/tests/Application.Tests.Unit/Authors/Queries/GetAuthorById/GetAuthorByIdValidatorTests.cs
new file mode 100644
index 0000000..a085266
--- /dev/null
+++ b/tests/Application.Tests.Unit/Authors/Queries/GetAuthorById/GetAuthorByIdValidatorTests.cs
@@ -0,0 +1,49 @@
+namespace CleanModelContextProtocol.Application.Tests.Unit.Authors.Queries.GetAuthorById;
+
+using Application.Authors.Queries.GetAuthorById;
+using FluentValidation.TestHelper;
+using Xunit;
+
+public class GetAuthorByIdQueryValidatorTests
+{
+ private static readonly GetAuthorByIdValidator Validator = new();
+
+ [Fact]
+ public void Validator_ShouldHaveValidationErrorFor_IdNull()
+ {
+ // Arrange
+ var query = new GetAuthorByIdQuery();
+
+ // Act
+ var result = Validator.TestValidate(query);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(query => query.Id);
+ }
+
+ [Fact]
+ public void Validator_ShouldHaveValidationErrorFor_IdEmpty()
+ {
+ // Arrange
+ var query = new GetAuthorByIdQuery { Id = Guid.Empty };
+
+ // Act
+ var result = Validator.TestValidate(query);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(query => query.Id);
+ }
+
+ [Fact]
+ public void Validator_ShouldNotHaveValidationErrorFor_Id()
+ {
+ // Arrange
+ var query = new GetAuthorByIdQuery { Id = Guid.NewGuid() };
+
+ // Act
+ var result = Validator.TestValidate(query);
+
+ // Assert
+ result.ShouldNotHaveValidationErrorFor(query => query.Id);
+ }
+}
diff --git a/tests/Application.Tests.Unit/Common/Behaviours/ValidationBehaviourTests.cs b/tests/Application.Tests.Unit/Common/Behaviours/ValidationBehaviourTests.cs
new file mode 100644
index 0000000..c31c1eb
--- /dev/null
+++ b/tests/Application.Tests.Unit/Common/Behaviours/ValidationBehaviourTests.cs
@@ -0,0 +1,62 @@
+namespace CleanModelContextProtocol.Application.Tests.Unit.Common.Behaviours;
+
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Application.Authors.Entities;
+using Application.Authors.Queries.GetAuthorById;
+using Application.Common.Behaviours;
+using FluentValidation;
+using Mediator;
+using NSubstitute;
+using Shouldly;
+using Xunit;
+
+public class ValidationBehaviourTests
+{
+ [Fact]
+ public async Task Handle_ShouldValidate_NoErrors()
+ {
+ // Arrange
+ var query = new GetAuthorByIdQuery { Id = Guid.NewGuid() };
+ var validators = new List> { new GetAuthorByIdValidator() };
+ var handler = new ValidationBehaviour(validators);
+ using var tokenSource = new CancellationTokenSource();
+ var token = tokenSource.Token;
+ var next = Substitute.For>();
+
+ _ = next(query, token).Returns(new Author(Guid.Empty, "Test", "Test"));
+
+ // Act
+ var result = await handler.Handle(query, next, token);
+
+ // Assert
+ _ = result.ShouldNotBeNull();
+ }
+
+ [Fact]
+ public void Handle_ShouldValidate_Errors()
+ {
+ // Arrange
+ var query = new GetAuthorByIdQuery { Id = Guid.Empty };
+ var validators = new List> { new GetAuthorByIdValidator() };
+ var handler = new ValidationBehaviour(validators);
+ using var tokenSource = new CancellationTokenSource();
+ var token = tokenSource.Token;
+ var next = Substitute.For>();
+
+ // Act
+ var exception = Should.Throw(async () => await handler.Handle(query, next, token));
+
+ // Assert
+ _ = exception.ShouldNotBeNull();
+ _ = exception.ShouldBeOfType();
+ exception.Errors.ShouldNotBeEmpty();
+
+ var errors = exception.Errors.ToList();
+
+ errors.Count.ShouldBe(1);
+ errors[0].PropertyName.ShouldBe("Id");
+ }
+}
diff --git a/tests/Application.Tests.Unit/Movies/Queries/GetMovieById/GetMovieByIdValidatorTests.cs b/tests/Application.Tests.Unit/Movies/Queries/GetMovieById/GetMovieByIdValidatorTests.cs
new file mode 100644
index 0000000..56d4f30
--- /dev/null
+++ b/tests/Application.Tests.Unit/Movies/Queries/GetMovieById/GetMovieByIdValidatorTests.cs
@@ -0,0 +1,49 @@
+namespace CleanModelContextProtocol.Application.Tests.Unit.Movies.Queries.GetMovieById;
+
+using Application.Movies.Queries.GetMovieById;
+using FluentValidation.TestHelper;
+using Xunit;
+
+public class GetMovieByIdValidatorTests
+{
+ private static readonly GetMovieByIdValidator Validator = new();
+
+ [Fact]
+ public void Validator_ShouldHaveValidationErrorFor_IdNull()
+ {
+ // Arrange
+ var query = new GetMovieByIdQuery();
+
+ // Act
+ var result = Validator.TestValidate(query);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(query => query.Id);
+ }
+
+ [Fact]
+ public void Validator_ShouldHaveValidationErrorFor_IdEmpty()
+ {
+ // Arrange
+ var query = new GetMovieByIdQuery { Id = Guid.Empty };
+
+ // Act
+ var result = Validator.TestValidate(query);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(query => query.Id);
+ }
+
+ [Fact]
+ public void Validator_ShouldNotHaveValidationErrorFor_Id()
+ {
+ // Arrange
+ var query = new GetMovieByIdQuery { Id = Guid.NewGuid() };
+
+ // Act
+ var result = Validator.TestValidate(query);
+
+ // Assert
+ result.ShouldNotHaveValidationErrorFor(query => query.Id);
+ }
+}
diff --git a/tests/Presentation.Tests.Unit/Validators/CreateReviewValidatorTests.cs b/tests/Application.Tests.Unit/Reviews/Commands/CreateReview/CreateReviewValidatorTests.cs
similarity index 53%
rename from tests/Presentation.Tests.Unit/Validators/CreateReviewValidatorTests.cs
rename to tests/Application.Tests.Unit/Reviews/Commands/CreateReview/CreateReviewValidatorTests.cs
index 034d36b..4face0f 100644
--- a/tests/Presentation.Tests.Unit/Validators/CreateReviewValidatorTests.cs
+++ b/tests/Application.Tests.Unit/Reviews/Commands/CreateReview/CreateReviewValidatorTests.cs
@@ -1,44 +1,36 @@
-namespace CleanModelContextProtocol.Presentation.Tests.Unit.Validators;
+namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Commands.CreateReview;
+using Application.Reviews.Commands.CreateReview;
using FluentValidation.TestHelper;
-using Presentation.Requests;
-using Presentation.Validators;
using Xunit;
public class CreateReviewValidatorTests
{
private static readonly CreateReviewValidator Validator = new();
- [Theory]
- [InlineData(1)]
- [InlineData(2)]
- [InlineData(3)]
- [InlineData(4)]
- [InlineData(5)]
- public void Validator_ShouldNotHaveValidationErrorFor_ValidRequest(int stars)
+ [Fact]
+ public void Validator_ShouldNotHaveValidationErrorFor_ReviewAuthorId()
{
// Arrange
- var command = new CreateReviewRequest
+ var command = new CreateReviewCommand
{
AuthorId = Guid.NewGuid(),
MovieId = Guid.NewGuid(),
- Stars = stars
+ Stars = 5
};
// Act
var result = Validator.TestValidate(command);
// Assert
- result.ShouldNotHaveValidationErrorFor(request => request.AuthorId);
- result.ShouldNotHaveValidationErrorFor(request => request.MovieId);
- result.ShouldNotHaveValidationErrorFor(request => request.Stars);
+ result.ShouldNotHaveValidationErrorFor(command => command.AuthorId);
}
[Fact]
public void Validator_ShouldHaveValidationErrorFor_ReviewAuthorId()
{
// Arrange
- var command = new CreateReviewRequest
+ var command = new CreateReviewCommand
{
AuthorId = Guid.Empty,
MovieId = Guid.NewGuid(),
@@ -49,18 +41,32 @@ public void Validator_ShouldHaveValidationErrorFor_ReviewAuthorId()
var result = Validator.TestValidate(command);
// Assert
- _ = result.ShouldHaveValidationErrorFor(command => command.AuthorId)
- .WithErrorMessage("An author id was not supplied to create the review.");
+ _ = result.ShouldHaveValidationErrorFor(command => command.AuthorId).WithErrorMessage("An author id was not supplied to create the review.");
+ }
+
+ [Fact]
+ public void Validator_ShouldNotHaveValidationErrorFor_ReviewedMovieId()
+ {
+ // Arrange
+ var command = new CreateReviewCommand
+ {
+ AuthorId = Guid.NewGuid(),
+ MovieId = Guid.NewGuid(),
+ Stars = 5
+ };
+
+ // Act
+ var result = Validator.TestValidate(command);
- result.ShouldNotHaveValidationErrorFor(request => request.MovieId);
- result.ShouldNotHaveValidationErrorFor(request => request.Stars);
+ // Assert
+ result.ShouldNotHaveValidationErrorFor(command => command.MovieId);
}
[Fact]
public void Validator_ShouldHaveValidationErrorFor_ReviewedMovieId()
{
// Arrange
- var command = new CreateReviewRequest
+ var command = new CreateReviewCommand
{
AuthorId = Guid.NewGuid(),
MovieId = Guid.Empty,
@@ -71,11 +77,31 @@ public void Validator_ShouldHaveValidationErrorFor_ReviewedMovieId()
var result = Validator.TestValidate(command);
// Assert
- _ = result.ShouldHaveValidationErrorFor(command => command.MovieId)
- .WithErrorMessage("A movie id was not supplied to create the review.");
+ _ = result.ShouldHaveValidationErrorFor(command => command.MovieId).WithErrorMessage("A movie id was not supplied to create the review.");
+ }
+
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(4)]
+ [InlineData(5)]
+ public void Validator_ShouldNotHaveValidationErrorFor_Stars(int stars)
+ {
+ // Arrange
+ var command = new CreateReviewCommand
+ {
+ AuthorId = Guid.NewGuid(),
+ MovieId = Guid.NewGuid(),
+ Stars = stars
+ };
- result.ShouldNotHaveValidationErrorFor(request => request.AuthorId);
- result.ShouldNotHaveValidationErrorFor(request => request.Stars);
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ result.ShouldNotHaveValidationErrorFor(command => command.Stars);
}
[Theory]
@@ -87,7 +113,7 @@ public void Validator_ShouldHaveValidationErrorFor_ReviewedMovieId()
public void Validator_ShouldHaveValidationErrorFor_Stars(int stars)
{
// Arrange
- var command = new CreateReviewRequest
+ var command = new CreateReviewCommand
{
AuthorId = Guid.NewGuid(),
MovieId = Guid.NewGuid(),
@@ -98,10 +124,6 @@ public void Validator_ShouldHaveValidationErrorFor_Stars(int stars)
var result = Validator.TestValidate(command);
// Assert
- _ = result.ShouldHaveValidationErrorFor(command => command.Stars)
- .WithErrorMessage("A star rating must be between 1 and 5.");
-
- result.ShouldNotHaveValidationErrorFor(request => request.AuthorId);
- result.ShouldNotHaveValidationErrorFor(request => request.MovieId);
+ _ = result.ShouldHaveValidationErrorFor(command => command.Stars).WithErrorMessage("A star rating must be between 1 and 5.");
}
}
diff --git a/tests/Application.Tests.Unit/Reviews/Commands/DeleteReview/DeleteReviewValidatorTests.cs b/tests/Application.Tests.Unit/Reviews/Commands/DeleteReview/DeleteReviewValidatorTests.cs
new file mode 100644
index 0000000..419d2cc
--- /dev/null
+++ b/tests/Application.Tests.Unit/Reviews/Commands/DeleteReview/DeleteReviewValidatorTests.cs
@@ -0,0 +1,49 @@
+namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Commands.DeleteReview;
+
+using Application.Reviews.Commands.DeleteReview;
+using FluentValidation.TestHelper;
+using Xunit;
+
+public class DeleteReviewValidatorTests
+{
+ private static readonly DeleteReviewValidator Validator = new();
+
+ [Fact]
+ public void Validator_ShouldHaveValidationErrorFor_IdNull()
+ {
+ // Arrange
+ var command = new DeleteReviewCommand();
+
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(command => command.Id);
+ }
+
+ [Fact]
+ public void Validator_ShouldHaveValidationErrorFor_IdEmpty()
+ {
+ // Arrange
+ var command = new DeleteReviewCommand { Id = Guid.Empty };
+
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(command => command.Id);
+ }
+
+ [Fact]
+ public void Validator_ShouldNotHaveValidationErrorFor_Id()
+ {
+ // Arrange
+ var command = new DeleteReviewCommand { Id = Guid.NewGuid() };
+
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ result.ShouldNotHaveValidationErrorFor(command => command.Id);
+ }
+}
diff --git a/tests/Application.Tests.Unit/Reviews/Commands/UpdateReview/UpdateReviewValidatorTests.cs b/tests/Application.Tests.Unit/Reviews/Commands/UpdateReview/UpdateReviewValidatorTests.cs
new file mode 100644
index 0000000..a20e674
--- /dev/null
+++ b/tests/Application.Tests.Unit/Reviews/Commands/UpdateReview/UpdateReviewValidatorTests.cs
@@ -0,0 +1,173 @@
+namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Commands.UpdateReview;
+
+using Application.Reviews.Commands.UpdateReview;
+using FluentValidation.TestHelper;
+using Xunit;
+
+public class UpdateReviewValidatorTests
+{
+ private static readonly UpdateReviewValidator Validator = new();
+
+ [Fact]
+ public void Validator_ShouldNotHaveValidationErrorFor_Id()
+ {
+ // Arrange
+ var command = new UpdateReviewCommand
+ {
+ Id = Guid.NewGuid(),
+ AuthorId = Guid.NewGuid(),
+ MovieId = Guid.NewGuid(),
+ Stars = 5
+ };
+
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ result.ShouldNotHaveValidationErrorFor(command => command.Id);
+ }
+
+ [Fact]
+ public void Validator_ShouldHaveValidationErrorFor_Id()
+ {
+ // Arrange
+ var command = new UpdateReviewCommand
+ {
+ Id = Guid.Empty,
+ AuthorId = Guid.NewGuid(),
+ MovieId = Guid.NewGuid(),
+ Stars = 5
+ };
+
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(command => command.Id).WithErrorMessage("A review id was not supplied to Update the review.");
+ }
+
+ [Fact]
+ public void Validator_ShouldNotHaveValidationErrorFor_ReviewAuthorId()
+ {
+ // Arrange
+ var command = new UpdateReviewCommand
+ {
+ Id = Guid.NewGuid(),
+ AuthorId = Guid.NewGuid(),
+ MovieId = Guid.NewGuid(),
+ Stars = 5
+ };
+
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ result.ShouldNotHaveValidationErrorFor(command => command.AuthorId);
+ }
+
+ [Fact]
+ public void Validator_ShouldHaveValidationErrorFor_ReviewAuthorId()
+ {
+ // Arrange
+ var command = new UpdateReviewCommand
+ {
+ Id = Guid.NewGuid(),
+ AuthorId = Guid.Empty,
+ MovieId = Guid.NewGuid(),
+ Stars = 5
+ };
+
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(command => command.AuthorId).WithErrorMessage("An author id was not supplied to Update the review.");
+ }
+
+ [Fact]
+ public void Validator_ShouldNotHaveValidationErrorFor_ReviewedMovieId()
+ {
+ // Arrange
+ var command = new UpdateReviewCommand
+ {
+ Id = Guid.NewGuid(),
+ AuthorId = Guid.NewGuid(),
+ MovieId = Guid.NewGuid(),
+ Stars = 5
+ };
+
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ result.ShouldNotHaveValidationErrorFor(command => command.MovieId);
+ }
+
+ [Fact]
+ public void Validator_ShouldHaveValidationErrorFor_ReviewedMovieId()
+ {
+ // Arrange
+ var command = new UpdateReviewCommand
+ {
+ Id = Guid.NewGuid(),
+ AuthorId = Guid.NewGuid(),
+ MovieId = Guid.Empty,
+ Stars = 5
+ };
+
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(command => command.MovieId).WithErrorMessage("A movie id was not supplied to Update the review.");
+ }
+
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(4)]
+ [InlineData(5)]
+ public void Validator_ShouldNotHaveValidationErrorFor_Stars(int stars)
+ {
+ // Arrange
+ var command = new UpdateReviewCommand
+ {
+ Id = Guid.NewGuid(),
+ AuthorId = Guid.NewGuid(),
+ MovieId = Guid.NewGuid(),
+ Stars = stars
+ };
+
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ result.ShouldNotHaveValidationErrorFor(command => command.Stars);
+ }
+
+ [Theory]
+ [InlineData(-1)]
+ [InlineData(0)]
+ [InlineData(6)]
+ [InlineData(100)]
+ [InlineData(-100)]
+ public void Validator_ShouldHaveValidationErrorFor_Stars(int stars)
+ {
+ // Arrange
+ var command = new UpdateReviewCommand
+ {
+ Id = Guid.NewGuid(),
+ AuthorId = Guid.NewGuid(),
+ MovieId = Guid.NewGuid(),
+ Stars = stars
+ };
+
+ // Act
+ var result = Validator.TestValidate(command);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(command => command.Stars).WithErrorMessage("A star rating must be between 1 and 5.");
+ }
+}
diff --git a/tests/Application.Tests.Unit/Reviews/Queries/GetReviewById/GetReviewByIdValidatorTests.cs b/tests/Application.Tests.Unit/Reviews/Queries/GetReviewById/GetReviewByIdValidatorTests.cs
new file mode 100644
index 0000000..9152f0f
--- /dev/null
+++ b/tests/Application.Tests.Unit/Reviews/Queries/GetReviewById/GetReviewByIdValidatorTests.cs
@@ -0,0 +1,49 @@
+namespace CleanModelContextProtocol.Application.Tests.Unit.Reviews.Queries.GetReviewById;
+
+using Application.Reviews.Queries.GetReviewById;
+using FluentValidation.TestHelper;
+using Xunit;
+
+public class GetReviewByIdValidatorTests
+{
+ private static readonly GetReviewByIdValidator Validator = new();
+
+ [Fact]
+ public void Validator_ShouldHaveValidationErrorFor_IdNull()
+ {
+ // Arrange
+ var query = new GetReviewByIdQuery();
+
+ // Act
+ var result = Validator.TestValidate(query);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(query => query.Id);
+ }
+
+ [Fact]
+ public void Validator_ShouldHaveValidationErrorFor_IdEmpty()
+ {
+ // Arrange
+ var query = new GetReviewByIdQuery { Id = Guid.Empty };
+
+ // Act
+ var result = Validator.TestValidate(query);
+
+ // Assert
+ _ = result.ShouldHaveValidationErrorFor(query => query.Id);
+ }
+
+ [Fact]
+ public void Validator_ShouldNotHaveValidationErrorFor_Id()
+ {
+ // Arrange
+ var query = new GetReviewByIdQuery { Id = Guid.NewGuid() };
+
+ // Act
+ var result = Validator.TestValidate(query);
+
+ // Assert
+ result.ShouldNotHaveValidationErrorFor(query => query.Id);
+ }
+}
diff --git a/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs b/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs
index d10b8d5..77c0dff 100644
--- a/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs
+++ b/tests/Presentation.Tests.Integration/Tools/AuthorToolTests.cs
@@ -79,28 +79,45 @@ public async Task GetAuthorById_ShouldReturn_Author()
}
}
+ [Fact]
+ public async Task GetAuthorById_WithEmptyId_ShouldReturn_ValidationError()
+ {
+ // Act
+ var result = await this.Client.CallToolAsync("GetAuthorById",
+ new Dictionary { ["id"] = Guid.Empty });
+ var text = result.Content.OfType().First().Text;
+
+ // Assert
+ result.IsError.ShouldBe(true);
+ text.ShouldBe("Validation Failed: Id: An Author Id was not supplied.");
+ }
+
+ [Fact]
+ public async Task GetAuthorById_WithUnknownId_ShouldReturn_NotFoundError()
+ {
+ // Act
+ var result = await this.Client.CallToolAsync("GetAuthorById",
+ new Dictionary { ["id"] = Guid.NewGuid() });
+ var text = result.Content.OfType().First().Text;
+
+ // Assert
+ result.IsError.ShouldBe(true);
+ text.ShouldBe("Not Found: The Author with the supplied id was not found.");
+ }
+
[Theory]
- [InlineData("00000000-0000-0000-0000-000000000000")]
[InlineData("1")]
[InlineData("fake")]
public async Task GetAuthorById_WithInvalidId_ShouldReturn_Error(string input)
{
- // Valid-format GUIDs (including empty) pass as Guid; unparseable strings pass as string
- object idArg = Guid.TryParse(input, out var guid) ? guid : input;
-
try
{
// Act
var result = await this.Client.CallToolAsync("GetAuthorById",
- new Dictionary { ["id"] = idArg });
-
- // Assert - empty GUID returns "Not Found:" text; binding errors may set IsError
- var isError = result.IsError == true;
- var textContent = result.Content.OfType().FirstOrDefault()?.Text ?? string.Empty;
- var isTextError = textContent.StartsWith("Not Found:", StringComparison.Ordinal)
- || textContent.StartsWith("Error:", StringComparison.Ordinal);
+ new Dictionary { ["id"] = input });
- (isError || isTextError).ShouldBeTrue();
+ // Assert
+ result.IsError.ShouldBe(true);
}
catch (McpException)
{
diff --git a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs
index ea1a200..5314d61 100644
--- a/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs
+++ b/tests/Presentation.Tests.Integration/Tools/MovieToolTests.cs
@@ -81,28 +81,45 @@ public async Task GetMovieById_ShouldReturn_Movie()
}
}
+ [Fact]
+ public async Task GetMovieById_WithEmptyId_ShouldReturn_ValidationError()
+ {
+ // Act
+ var result = await this.Client.CallToolAsync("GetMovieById",
+ new Dictionary { ["id"] = Guid.Empty });
+ var text = result.Content.OfType().First().Text;
+
+ // Assert
+ result.IsError.ShouldBe(true);
+ text.ShouldBe("Validation Failed: Id: A Movie Id was not supplied.");
+ }
+
+ [Fact]
+ public async Task GetMovieById_WithUnknownId_ShouldReturn_NotFoundError()
+ {
+ // Act
+ var result = await this.Client.CallToolAsync("GetMovieById",
+ new Dictionary { ["id"] = Guid.NewGuid() });
+ var text = result.Content.OfType().First().Text;
+
+ // Assert
+ result.IsError.ShouldBe(true);
+ text.ShouldBe("Not Found: The Movie with the supplied id was not found.");
+ }
+
[Theory]
- [InlineData("00000000-0000-0000-0000-000000000000")]
[InlineData("1")]
[InlineData("fake")]
public async Task GetMovieById_WithInvalidId_ShouldReturn_Error(string input)
{
- // Valid-format GUIDs (including empty) pass as Guid; unparseable strings pass as string
- object idArg = Guid.TryParse(input, out var guid) ? guid : input;
-
try
{
// Act
var result = await this.Client.CallToolAsync("GetMovieById",
- new Dictionary { ["id"] = idArg });
-
- // Assert - empty GUID returns "Not Found:" text; binding errors may set IsError
- var isError = result.IsError == true;
- var textContent = result.Content.OfType().FirstOrDefault()?.Text ?? string.Empty;
- var isTextError = textContent.StartsWith("Not Found:", StringComparison.Ordinal)
- || textContent.StartsWith("Error:", StringComparison.Ordinal);
+ new Dictionary { ["id"] = input });
- (isError || isTextError).ShouldBeTrue();
+ // Assert
+ result.IsError.ShouldBe(true);
}
catch (McpException)
{
diff --git a/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs b/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs
index e8be9b5..41c984d 100644
--- a/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs
+++ b/tests/Presentation.Tests.Integration/Tools/ReviewToolTests.cs
@@ -193,28 +193,45 @@ public async Task DeleteReview_ShouldReturn_Success()
validateText.ShouldStartWith("Not Found:");
}
+ [Fact]
+ public async Task GetReviewById_WithEmptyId_ShouldReturn_ValidationError()
+ {
+ // Act
+ var result = await this.Client.CallToolAsync("GetReviewById",
+ new Dictionary { ["id"] = Guid.Empty });
+ var text = result.Content.OfType().First().Text;
+
+ // Assert
+ result.IsError.ShouldBe(true);
+ text.ShouldBe("Validation Failed: Id: A Review Id was not supplied.");
+ }
+
+ [Fact]
+ public async Task GetReviewById_WithUnknownId_ShouldReturn_NotFoundError()
+ {
+ // Act
+ var result = await this.Client.CallToolAsync("GetReviewById",
+ new Dictionary { ["id"] = Guid.NewGuid() });
+ var text = result.Content.OfType().First().Text;
+
+ // Assert
+ result.IsError.ShouldBe(true);
+ text.ShouldBe("Not Found: The Review with the supplied id was not found.");
+ }
+
[Theory]
- [InlineData("00000000-0000-0000-0000-000000000000")]
[InlineData("1")]
[InlineData("fake")]
public async Task GetReviewById_WithInvalidId_ShouldReturn_Error(string input)
{
- // Valid-format GUIDs (including empty) pass as Guid; unparseable strings pass as string
- object idArg = Guid.TryParse(input, out var guid) ? guid : input;
-
try
{
// Act
var result = await this.Client.CallToolAsync("GetReviewById",
- new Dictionary { ["id"] = idArg });
-
- // Assert - empty GUID returns "Not Found:" text; binding errors may set IsError
- var isError = result.IsError == true;
- var textContent = result.Content.OfType().FirstOrDefault()?.Text ?? string.Empty;
- var isTextError = textContent.StartsWith("Not Found:", StringComparison.Ordinal)
- || textContent.StartsWith("Error:", StringComparison.Ordinal);
+ new Dictionary { ["id"] = input });
- (isError || isTextError).ShouldBeTrue();
+ // Assert
+ result.IsError.ShouldBe(true);
}
catch (McpException)
{
diff --git a/tests/Presentation.Tests.Unit/Errors/ToolErrorFilterTests.cs b/tests/Presentation.Tests.Unit/Errors/ToolErrorFilterTests.cs
new file mode 100644
index 0000000..b94e727
--- /dev/null
+++ b/tests/Presentation.Tests.Unit/Errors/ToolErrorFilterTests.cs
@@ -0,0 +1,81 @@
+namespace CleanModelContextProtocol.Presentation.Tests.Unit.Errors;
+
+using CleanModelContextProtocol.Application.Common.Exceptions;
+using CleanModelContextProtocol.Presentation.Errors;
+using FluentValidation;
+using FluentValidation.Results;
+using ModelContextProtocol.Protocol;
+using Shouldly;
+using Xunit;
+
+public class ToolErrorFilterTests
+{
+ [Fact]
+ public async Task Filter_ShouldReturn_Result()
+ {
+ // Arrange
+ var expected = new CallToolResult { Content = [new TextContentBlock { Text = "Lorem Ipsum" }] };
+ var handler = ToolErrorFilter.Filter((request, cancellationToken) => ValueTask.FromResult(expected));
+
+ // Act
+ var result = await handler(null!, CancellationToken.None);
+
+ // Assert
+ result.ShouldBe(expected);
+ }
+
+ [Fact]
+ public async Task Filter_ShouldReturn_ErrorResult()
+ {
+ // Arrange
+ var handler = ToolErrorFilter.Filter((request, cancellationToken) => throw new NotFoundException("Expected Exception"));
+
+ // Act
+ var result = await handler(null!, CancellationToken.None);
+
+ // Assert
+ result.IsError.ShouldBe(true);
+ result.Content.OfType().Single().Text.ShouldBe("Not Found: Expected Exception");
+ }
+
+ [Fact]
+ public void ToResult_ShouldReturn_ValidationError()
+ {
+ // Arrange
+ var exception = new ValidationException(
+ [
+ new ValidationFailure("AuthorId", "An author id was not supplied to create the review."),
+ new ValidationFailure("Stars", "A star rating must be between 1 and 5.")
+ ]);
+
+ // Act
+ var result = ToolErrorFilter.ToResult(exception);
+
+ // Assert
+ result.IsError.ShouldBe(true);
+ result.Content.OfType().Single().Text
+ .ShouldBe("Validation Failed: AuthorId: An author id was not supplied to create the review. Stars: A star rating must be between 1 and 5.");
+ }
+
+ [Fact]
+ public void ToResult_ShouldReturn_NotFoundError()
+ {
+ // Act
+ var result = ToolErrorFilter.ToResult(new NotFoundException("Expected Exception"));
+
+ // Assert
+ result.IsError.ShouldBe(true);
+ result.Content.OfType().Single().Text.ShouldBe("Not Found: Expected Exception");
+ }
+
+ [Fact]
+ public void ToResult_ShouldReturn_Error()
+ {
+ // Act
+ var result = ToolErrorFilter.ToResult(new ArgumentException("Expected Exception"));
+
+ // Assert
+ result.IsError.ShouldBe(true);
+ result.Content.OfType().Single().Text.ShouldBe("Error: An error occurred while processing your request.");
+ }
+}
diff --git a/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs b/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs
index 9cb3301..e98855a 100644
--- a/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs
+++ b/tests/Presentation.Tests.Unit/Tools/AuthorToolTests.cs
@@ -1,11 +1,9 @@
namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools;
using System.Text.Json;
-using CleanModelContextProtocol.Application.Common.Exceptions;
using CleanModelContextProtocol.Presentation.Tools;
-using MediatR;
+using Mediator;
using NSubstitute;
-using NSubstitute.ExceptionExtensions;
using Shouldly;
using Xunit;
using Entities = Application.Authors.Entities;
@@ -41,23 +39,6 @@ public async Task GetAllAuthors_ShouldReturn_JsonResult()
result[0].Reviews.ShouldBeNull();
}
- [Fact]
- public async Task GetAllAuthors_ShouldReturn_Error()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new ArgumentException("Expected Exception"));
-
- // Act
- var response = await AuthorTools.GetAllAuthors(sender);
-
- // Assert
- response.ShouldBe("Error: Expected Exception");
- }
-
[Fact]
public async Task GetAuthorById_ShouldReturn_JsonResult()
{
@@ -80,38 +61,4 @@ public async Task GetAuthorById_ShouldReturn_JsonResult()
result.LastName.ShouldBe("Ipsum");
result.Reviews.ShouldBeNull();
}
-
- [Fact]
- public async Task GetAuthorById_ShouldReturn_NotFound()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new NotFoundException("Expected Exception"));
-
- // Act
- var response = await AuthorTools.GetAuthorById(sender, Guid.Empty);
-
- // Assert
- response.ShouldBe("Not Found: Expected Exception");
- }
-
- [Fact]
- public async Task GetAuthorById_ShouldReturn_Error()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new ArgumentException("Expected Exception"));
-
- // Act
- var response = await AuthorTools.GetAuthorById(sender, Guid.Empty);
-
- // Assert
- response.ShouldBe("Error: Expected Exception");
- }
}
diff --git a/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs b/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs
index 3d8c783..a939450 100644
--- a/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs
+++ b/tests/Presentation.Tests.Unit/Tools/MovieToolTests.cs
@@ -1,11 +1,9 @@
namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools;
using System.Text.Json;
-using CleanModelContextProtocol.Application.Common.Exceptions;
using CleanModelContextProtocol.Presentation.Tools;
-using MediatR;
+using Mediator;
using NSubstitute;
-using NSubstitute.ExceptionExtensions;
using Shouldly;
using Xunit;
using Entities = Application.Movies.Entities;
@@ -40,23 +38,6 @@ public async Task GetAllMovies_ShouldReturn_JsonResult()
result[0].Reviews.ShouldBeNull();
}
- [Fact]
- public async Task GetAllMovies_ShouldReturn_Error()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new ArgumentException("Expected Exception"));
-
- // Act
- var response = await MovieTools.GetAllMovies(sender);
-
- // Assert
- response.ShouldBe("Error: Expected Exception");
- }
-
[Fact]
public async Task GetMovieById_ShouldReturn_JsonResult()
{
@@ -78,38 +59,4 @@ public async Task GetMovieById_ShouldReturn_JsonResult()
result.Title.ShouldBe("Lorem Ipsum");
result.Reviews.ShouldBeNull();
}
-
- [Fact]
- public async Task GetMovieById_ShouldReturn_NotFound()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new NotFoundException("Expected Exception"));
-
- // Act
- var response = await MovieTools.GetMovieById(sender, Guid.Empty);
-
- // Assert
- response.ShouldBe("Not Found: Expected Exception");
- }
-
- [Fact]
- public async Task GetMovieById_ShouldReturn_Error()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new ArgumentException("Expected Exception"));
-
- // Act
- var response = await MovieTools.GetMovieById(sender, Guid.Empty);
-
- // Assert
- response.ShouldBe("Error: Expected Exception");
- }
}
diff --git a/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs b/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs
index 786b02b..abb1aa7 100644
--- a/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs
+++ b/tests/Presentation.Tests.Unit/Tools/ReviewToolTests.cs
@@ -3,11 +3,9 @@ namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools;
using System.Text.Json;
using Application.Authors.Entities;
using Application.Movies.Entities;
-using CleanModelContextProtocol.Application.Common.Exceptions;
using CleanModelContextProtocol.Presentation.Tools;
-using MediatR;
+using Mediator;
using NSubstitute;
-using NSubstitute.ExceptionExtensions;
using Shouldly;
using Xunit;
using Commands = Application.Reviews.Commands;
@@ -53,23 +51,6 @@ public async Task GetAllReviews_ShouldReturn_JsonResult()
result[0].ReviewedMovie.Title.ShouldBe("Lorem Ipsum");
}
- [Fact]
- public async Task GetAllReviews_ShouldReturn_Error()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new ArgumentException("Expected Exception"));
-
- // Act
- var response = await ReviewTools.GetAllReviews(sender);
-
- // Assert
- response.ShouldBe("Error: Expected Exception");
- }
-
[Fact]
public async Task GetReviewById_ShouldReturn_JsonResult()
{
@@ -96,40 +77,6 @@ public async Task GetReviewById_ShouldReturn_JsonResult()
result.ReviewedMovie.Title.ShouldBe("Lorem Ipsum");
}
- [Fact]
- public async Task GetReviewById_ShouldReturn_NotFound()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new NotFoundException("Expected Exception"));
-
- // Act
- var response = await ReviewTools.GetReviewById(sender, Guid.Empty);
-
- // Assert
- response.ShouldBe("Not Found: Expected Exception");
- }
-
- [Fact]
- public async Task GetReviewById_ShouldReturn_Error()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new ArgumentException("Expected Exception"));
-
- // Act
- var response = await ReviewTools.GetReviewById(sender, Guid.Empty);
-
- // Assert
- response.ShouldBe("Error: Expected Exception");
- }
-
[Fact]
public async Task CreateReview_ShouldReturn_JsonResult()
{
@@ -156,40 +103,6 @@ public async Task CreateReview_ShouldReturn_JsonResult()
result.ReviewedMovie.Title.ShouldBe("Lorem Ipsum");
}
- [Fact]
- public async Task CreateReview_ShouldReturn_NotFound()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new NotFoundException("Expected Exception"));
-
- // Act
- var response = await ReviewTools.CreateReview(sender, Guid.Empty, Guid.Empty, 5);
-
- // Assert
- response.ShouldBe("Not Found: Expected Exception");
- }
-
- [Fact]
- public async Task CreateReview_ShouldReturn_Error()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new ArgumentException("Expected Exception"));
-
- // Act
- var response = await ReviewTools.CreateReview(sender, Guid.Empty, Guid.Empty, 5);
-
- // Assert
- response.ShouldBe("Error: Expected Exception");
- }
-
[Fact]
public async Task UpdateReview_ShouldReturn_Success()
{
@@ -207,40 +120,6 @@ public async Task UpdateReview_ShouldReturn_Success()
response.ShouldBe("Review updated successfully");
}
- [Fact]
- public async Task UpdateReview_ShouldReturn_NotFound()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new NotFoundException("Expected Exception"));
-
- // Act
- var response = await ReviewTools.UpdateReview(sender, Guid.Empty, Guid.Empty, Guid.Empty, 5);
-
- // Assert
- response.ShouldBe("Not Found: Expected Exception");
- }
-
- [Fact]
- public async Task UpdateReview_ShouldReturn_Error()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new ArgumentException("Expected Exception"));
-
- // Act
- var response = await ReviewTools.UpdateReview(sender, Guid.Empty, Guid.Empty, Guid.Empty, 5);
-
- // Assert
- response.ShouldBe("Error: Expected Exception");
- }
-
[Fact]
public async Task DeleteReview_ShouldReturn_Success()
{
@@ -257,38 +136,4 @@ public async Task DeleteReview_ShouldReturn_Success()
// Assert
response.ShouldBe("Review deleted successfully");
}
-
- [Fact]
- public async Task DeleteReview_ShouldReturn_NotFound()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new NotFoundException("Expected Exception"));
-
- // Act
- var response = await ReviewTools.DeleteReview(sender, Guid.Empty);
-
- // Assert
- response.ShouldBe("Not Found: Expected Exception");
- }
-
- [Fact]
- public async Task DeleteReview_ShouldReturn_Error()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new ArgumentException("Expected Exception"));
-
- // Act
- var response = await ReviewTools.DeleteReview(sender, Guid.Empty);
-
- // Assert
- response.ShouldBe("Error: Expected Exception");
- }
}
diff --git a/tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs b/tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs
index ba7f541..19693de 100644
--- a/tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs
+++ b/tests/Presentation.Tests.Unit/Tools/VersionToolTests.cs
@@ -1,9 +1,8 @@
namespace CleanModelContextProtocol.Presentation.Tests.Unit.Tools;
using CleanModelContextProtocol.Presentation.Tools;
-using MediatR;
+using Mediator;
using NSubstitute;
-using NSubstitute.ExceptionExtensions;
using Shouldly;
using Xunit;
using Entities = Application.Versions.Entities;
@@ -32,21 +31,4 @@ public async Task GetVersion_ShouldReturn_MarkdownTable()
response.ShouldContain("| File Version | 1.2.3.4 |");
response.ShouldContain("| Informational Version | 5.6.7.8 |");
}
-
- [Fact]
- public async Task GetVersion_ShouldReturn_Error()
- {
- // Arrange
- var sender = Substitute.For();
-
- _ = sender
- .Send(Arg.Any())
- .Throws(new ArgumentException("Expected Exception"));
-
- // Act
- var response = await VersionTools.GetVersion(sender);
-
- // Assert
- response.ShouldBe("Error: Expected Exception");
- }
}
diff --git a/tests/Presentation.Tests.Unit/Validators/GenericIdentityValidatorTests.cs b/tests/Presentation.Tests.Unit/Validators/GenericIdentityValidatorTests.cs
deleted file mode 100644
index b7fa7f8..0000000
--- a/tests/Presentation.Tests.Unit/Validators/GenericIdentityValidatorTests.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-namespace CleanModelContextProtocol.Presentation.Tests.Unit.Validators;
-
-using CleanModelContextProtocol.Presentation.Validators;
-using FluentValidation.TestHelper;
-using Xunit;
-
-public class GenericIdentityValidatorTests
-{
- private static readonly GenericIdentityValidator Validator = new();
-
- [Fact]
- public void Validator_ShouldNotHaveValidationErrorFor_Guid()
- {
- // Arrange
- var guid = Guid.NewGuid();
-
- // Act
- var result = Validator.TestValidate(guid);
-
- // Assert
- result.ShouldNotHaveValidationErrorFor(guid => guid);
- }
-
- [Fact]
- public void Validator_ShouldHaveValidationErrorFor_Empty()
- {
- // Arrange
- var guid = Guid.Empty;
-
- // Act
- var result = Validator.TestValidate(guid);
-
- // Assert
- _ = result.ShouldHaveValidationErrorFor(guid => guid);
- }
-}
diff --git a/tests/Presentation.Tests.Unit/Validators/UpdateReviewValidatorTests.cs b/tests/Presentation.Tests.Unit/Validators/UpdateReviewValidatorTests.cs
deleted file mode 100644
index 0e9b8f9..0000000
--- a/tests/Presentation.Tests.Unit/Validators/UpdateReviewValidatorTests.cs
+++ /dev/null
@@ -1,107 +0,0 @@
-namespace CleanModelContextProtocol.Presentation.Tests.Unit.Validators;
-
-using FluentValidation.TestHelper;
-using Presentation.Requests;
-using Presentation.Validators;
-using Xunit;
-
-public class UpdateReviewValidatorTests
-{
- private static readonly UpdateReviewValidator Validator = new();
-
- [Theory]
- [InlineData(1)]
- [InlineData(2)]
- [InlineData(3)]
- [InlineData(4)]
- [InlineData(5)]
- public void Validator_ShouldNotHaveValidationErrorFor_ReviewAuthorId(int stars)
- {
- // Arrange
- var request = new UpdateReviewRequest
- {
- AuthorId = Guid.NewGuid(),
- MovieId = Guid.NewGuid(),
- Stars = stars
- };
-
- // Act
- var result = Validator.TestValidate(request);
-
- // Assert
- result.ShouldNotHaveValidationErrorFor(request => request.AuthorId);
- result.ShouldNotHaveValidationErrorFor(request => request.MovieId);
- result.ShouldNotHaveValidationErrorFor(request => request.Stars);
- }
-
- [Fact]
- public void Validator_ShouldHaveValidationErrorFor_ReviewAuthorId()
- {
- // Arrange
- var request = new UpdateReviewRequest
- {
- AuthorId = Guid.Empty,
- MovieId = Guid.NewGuid(),
- Stars = 5
- };
-
- // Act
- var result = Validator.TestValidate(request);
-
- // Assert
- _ = result.ShouldHaveValidationErrorFor(request => request.AuthorId)
- .WithErrorMessage("An author id was not supplied to Update the review.");
-
- result.ShouldNotHaveValidationErrorFor(request => request.MovieId);
- result.ShouldNotHaveValidationErrorFor(request => request.Stars);
- }
-
- [Fact]
- public void Validator_ShouldHaveValidationErrorFor_ReviewedMovieId()
- {
- // Arrange
- var request = new UpdateReviewRequest
- {
- AuthorId = Guid.NewGuid(),
- MovieId = Guid.Empty,
- Stars = 5
- };
-
- // Act
- var result = Validator.TestValidate(request);
-
- // Assert
- _ = result.ShouldHaveValidationErrorFor(request => request.MovieId)
- .WithErrorMessage("A movie id was not supplied to Update the review.");
-
- result.ShouldNotHaveValidationErrorFor(request => request.AuthorId);
- result.ShouldNotHaveValidationErrorFor(request => request.Stars);
- }
-
- [Theory]
- [InlineData(-1)]
- [InlineData(0)]
- [InlineData(6)]
- [InlineData(100)]
- [InlineData(-100)]
- public void Validator_ShouldHaveValidationErrorFor_Stars(int stars)
- {
- // Arrange
- var request = new UpdateReviewRequest
- {
- AuthorId = Guid.NewGuid(),
- MovieId = Guid.NewGuid(),
- Stars = stars
- };
-
- // Act
- var result = Validator.TestValidate(request);
-
- // Assert
- _ = result.ShouldHaveValidationErrorFor(request => request.Stars)
- .WithErrorMessage("A star rating must be between 1 and 5.");
-
- result.ShouldNotHaveValidationErrorFor(request => request.AuthorId);
- result.ShouldNotHaveValidationErrorFor(request => request.MovieId);
- }
-}