Skip to content

Commit

Permalink
Merge pull request #1338 from json-api-dotnet/remove-moq-usage
Browse files Browse the repository at this point in the history
Remove Moq usage
  • Loading branch information
bkoelman authored Sep 19, 2023
2 parents a3418fe + 83b5d00 commit 9e4e9c8
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 72 deletions.
1 change: 0 additions & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
<PropertyGroup>
<CoverletVersion>6.0.*</CoverletVersion>
<GitHubActionsTestLoggerVersion>2.3.*</GitHubActionsTestLoggerVersion>
<MoqVersion>4.18.*</MoqVersion>
<TestSdkVersion>17.7.*</TestSdkVersion>
</PropertyGroup>
</Project>
13 changes: 9 additions & 4 deletions src/JsonApiDotNetCore/Middleware/JsonApiMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ public sealed class JsonApiMiddleware
private static readonly MediaTypeHeaderValue MediaType = MediaTypeHeaderValue.Parse(HeaderConstants.MediaType);
private static readonly MediaTypeHeaderValue AtomicOperationsMediaType = MediaTypeHeaderValue.Parse(HeaderConstants.AtomicOperationsMediaType);

private readonly RequestDelegate _next;
private readonly RequestDelegate? _next;

public JsonApiMiddleware(RequestDelegate next, IHttpContextAccessor httpContextAccessor)
public JsonApiMiddleware(RequestDelegate? next, IHttpContextAccessor httpContextAccessor)
{
ArgumentGuard.NotNull(httpContextAccessor);

_next = next;

var session = new AspNetCodeTimerSession(httpContextAccessor);
Expand Down Expand Up @@ -77,9 +79,12 @@ public async Task InvokeAsync(HttpContext httpContext, IControllerResourceMappin
httpContext.RegisterJsonApiRequest();
}

using (CodeTimingSessionManager.Current.Measure("Subsequent middleware"))
if (_next != null)
{
await _next(httpContext);
using (CodeTimingSessionManager.Current.Measure("Subsequent middleware"))
{
await _next(httpContext);
}
}
}

Expand Down
2 changes: 0 additions & 2 deletions src/JsonApiDotNetCore/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,3 @@
[assembly: InternalsVisibleTo("Benchmarks")]
[assembly: InternalsVisibleTo("JsonApiDotNetCoreTests")]
[assembly: InternalsVisibleTo("UnitTests")]
[assembly: InternalsVisibleTo("DiscoveryTests")]
[assembly: InternalsVisibleTo("TestBuildingBlocks")]
1 change: 0 additions & 1 deletion test/DiscoveryTests/DiscoveryTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,5 @@
<PackageReference Include="coverlet.collector" Version="$(CoverletVersion)" PrivateAssets="All" />
<PackageReference Include="GitHubActionsTestLogger" Version="$(GitHubActionsTestLoggerVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(TestSdkVersion)" />
<PackageReference Include="Moq" Version="$(MoqVersion)" />
</ItemGroup>
</Project>
95 changes: 45 additions & 50 deletions test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using FluentAssertions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.Queries;
using JsonApiDotNetCore.Repositories;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Services;
Expand All @@ -10,53 +8,33 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using TestBuildingBlocks;
using Xunit;

namespace DiscoveryTests;

public sealed class ServiceDiscoveryFacadeTests
{
private static readonly ILoggerFactory LoggerFactory = NullLoggerFactory.Instance;
private readonly IServiceCollection _services = new ServiceCollection();
private readonly ResourceGraphBuilder _resourceGraphBuilder;
private readonly ServiceCollection _services = new();

public ServiceDiscoveryFacadeTests()
{
var dbResolverMock = new Mock<IDbContextResolver>();
dbResolverMock.Setup(resolver => resolver.GetContext()).Returns(new Mock<DbContext>().Object);
_services.AddScoped(_ => dbResolverMock.Object);

IJsonApiOptions options = new JsonApiOptions();

_services.AddSingleton(options);
_services.AddSingleton(LoggerFactory);
_services.AddScoped(_ => new Mock<IJsonApiRequest>().Object);
_services.AddScoped(_ => new Mock<ITargetedFields>().Object);
_services.AddScoped(_ => new Mock<IResourceGraph>().Object);
_services.AddScoped(typeof(IResourceChangeTracker<>), typeof(ResourceChangeTracker<>));
_services.AddScoped(_ => new Mock<IResourceFactory>().Object);
_services.AddScoped(_ => new Mock<IPaginationContext>().Object);
_services.AddScoped(_ => new Mock<IQueryLayerComposer>().Object);
_services.AddScoped(_ => new Mock<IResourceRepositoryAccessor>().Object);
_services.AddScoped(_ => new Mock<IResourceDefinitionAccessor>().Object);

_resourceGraphBuilder = new ResourceGraphBuilder(options, LoggerFactory);
_services.AddSingleton<ILoggerFactory>(_ => NullLoggerFactory.Instance);
_services.AddScoped<IDbContextResolver>(_ => new FakeDbContextResolver());
}

[Fact]
public void Can_add_resources_from_assembly_to_graph()
{
// Arrange
var facade = new ServiceDiscoveryFacade(_services, _resourceGraphBuilder, LoggerFactory);
facade.AddAssembly(typeof(Person).Assembly);
Action<ServiceDiscoveryFacade> addAction = facade => facade.AddAssembly(typeof(Person).Assembly);

Check notice on line 30 in test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Convert delegate variable into local function

Use local function

// Act
facade.DiscoverResources();
_services.AddJsonApi(discovery: facade => addAction(facade));

// Assert
IResourceGraph resourceGraph = _resourceGraphBuilder.Build();
ServiceProvider serviceProvider = _services.BuildServiceProvider();
var resourceGraph = serviceProvider.GetRequiredService<IResourceGraph>();

ResourceType? personType = resourceGraph.FindResourceType(typeof(Person));
personType.ShouldNotBeNull();
Expand All @@ -69,67 +47,84 @@ public void Can_add_resources_from_assembly_to_graph()
public void Can_add_resource_from_current_assembly_to_graph()
{
// Arrange
var facade = new ServiceDiscoveryFacade(_services, _resourceGraphBuilder, LoggerFactory);
facade.AddCurrentAssembly();
Action<ServiceDiscoveryFacade> addAction = facade => facade.AddCurrentAssembly();

Check notice on line 50 in test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Convert delegate variable into local function

Use local function

// Act
facade.DiscoverResources();
_services.AddJsonApi(discovery: facade => addAction(facade));

// Assert
IResourceGraph resourceGraph = _resourceGraphBuilder.Build();
ServiceProvider serviceProvider = _services.BuildServiceProvider();
var resourceGraph = serviceProvider.GetRequiredService<IResourceGraph>();

ResourceType? testResourceType = resourceGraph.FindResourceType(typeof(PrivateResource));
testResourceType.ShouldNotBeNull();
ResourceType? resourceType = resourceGraph.FindResourceType(typeof(PrivateResource));
resourceType.ShouldNotBeNull();
}

[Fact]
public void Can_add_resource_service_from_current_assembly_to_container()
{
// Arrange
var facade = new ServiceDiscoveryFacade(_services, _resourceGraphBuilder, LoggerFactory);
facade.AddCurrentAssembly();
Action<ServiceDiscoveryFacade> addAction = facade => facade.AddCurrentAssembly();

Check notice on line 67 in test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Convert delegate variable into local function

Use local function

// Act
facade.DiscoverInjectables();
_services.AddJsonApi(discovery: facade => addAction(facade));

// Assert
ServiceProvider services = _services.BuildServiceProvider();
ServiceProvider serviceProvider = _services.BuildServiceProvider();
var resourceService = serviceProvider.GetRequiredService<IResourceService<PrivateResource, int>>();

var resourceService = services.GetRequiredService<IResourceService<PrivateResource, int>>();
resourceService.Should().BeOfType<PrivateResourceService>();
}

[Fact]
public void Can_add_resource_repository_from_current_assembly_to_container()
{
// Arrange
var facade = new ServiceDiscoveryFacade(_services, _resourceGraphBuilder, LoggerFactory);
facade.AddCurrentAssembly();
Action<ServiceDiscoveryFacade> addAction = facade => facade.AddCurrentAssembly();

Check notice on line 83 in test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Convert delegate variable into local function

Use local function

// Act
facade.DiscoverInjectables();
_services.AddJsonApi(discovery: facade => addAction(facade));

// Assert
ServiceProvider services = _services.BuildServiceProvider();
ServiceProvider serviceProvider = _services.BuildServiceProvider();
var resourceRepository = serviceProvider.GetRequiredService<IResourceRepository<PrivateResource, int>>();

var resourceRepository = services.GetRequiredService<IResourceRepository<PrivateResource, int>>();
resourceRepository.Should().BeOfType<PrivateResourceRepository>();
}

[Fact]
public void Can_add_resource_definition_from_current_assembly_to_container()
{
// Arrange
var facade = new ServiceDiscoveryFacade(_services, _resourceGraphBuilder, LoggerFactory);
facade.AddCurrentAssembly();
Action<ServiceDiscoveryFacade> addAction = facade => facade.AddCurrentAssembly();

Check notice on line 99 in test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs

View workflow job for this annotation

GitHub Actions / Qodana for .NET

Convert delegate variable into local function

Use local function

// Act
facade.DiscoverInjectables();
_services.AddJsonApi(discovery: facade => addAction(facade));

// Assert
ServiceProvider services = _services.BuildServiceProvider();
ServiceProvider serviceProvider = _services.BuildServiceProvider();
var resourceDefinition = serviceProvider.GetRequiredService<IResourceDefinition<PrivateResource, int>>();

var resourceDefinition = services.GetRequiredService<IResourceDefinition<PrivateResource, int>>();
resourceDefinition.Should().BeOfType<PrivateResourceDefinition>();
}

private sealed class FakeDbContextResolver : IDbContextResolver
{
private readonly FakeDbContextOptions _dbContextOptions = new();

public DbContext GetContext()
{
return new DbContext(_dbContextOptions);
}

private sealed class FakeDbContextOptions : DbContextOptions
{
public override Type ContextType => typeof(object);

public override DbContextOptions WithExtension<TExtension>(TExtension extension)
{
return this;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@
using JsonApiDotNetCore.Resources.Annotations;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using TestBuildingBlocks;
using Xunit;

#pragma warning disable AV1561 // Signature contains too many parameters

namespace UnitTests.Middleware;
namespace JsonApiDotNetCoreTests.UnitTests.Middleware;

public sealed class JsonApiRequestTests
public sealed class JsonApiMiddlewareTests
{
// @formatter:wrap_lines false
[Theory]
Expand Down Expand Up @@ -65,7 +65,7 @@ public async Task Sets_request_properties_correctly(string requestMethod, string
var httpContext = new DefaultHttpContext();
IControllerResourceMapping controllerResourceMapping = SetupRoutes(httpContext, resourceGraph, requestMethod, requestPath);

var middleware = new JsonApiMiddleware(_ => Task.CompletedTask, new HttpContextAccessor
var middleware = new JsonApiMiddleware(null, new HttpContextAccessor
{
HttpContext = httpContext
});
Expand Down Expand Up @@ -153,16 +153,10 @@ private static IControllerResourceMapping SetupRoutes(HttpContext httpContext, I
ControllerTypeInfo = (TypeInfo)typeof(object)
};

var controllerResourceMappingMock = new Mock<IControllerResourceMapping>();
httpContext.SetEndpoint(new Endpoint(null, new EndpointMetadataCollection(controllerActionDescriptor), null));

controllerResourceMappingMock.Setup(mapping => mapping.GetResourceTypeForController(It.IsAny<Type>())).Returns(() =>
{
return pathSegments.Length > 0 ? resourceGraph.GetResourceTypes().FirstOrDefault(resourceType => resourceType.PublicName == pathSegments[0]) : null;
});

httpContext.SetEndpoint(new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(controllerActionDescriptor), null));

return controllerResourceMappingMock.Object;
string? resourceTypePublicName = pathSegments.Length > 0 ? pathSegments[0] : null;
return new FakeJsonApiRoutingConvention(resourceGraph, resourceTypePublicName);
}

public enum IsReadOnly
Expand Down Expand Up @@ -198,4 +192,31 @@ private sealed class TodoItem : Identifiable<int>
[HasMany]
public ISet<ItemTag> Tags { get; set; } = new HashSet<ItemTag>();
}

private sealed class FakeJsonApiRoutingConvention : IJsonApiRoutingConvention
{
private readonly IResourceGraph _resourceGraph;
private readonly string? _resourceTypePublicName;

public FakeJsonApiRoutingConvention(IResourceGraph resourceGraph, string? resourceTypePublicName)
{
_resourceGraph = resourceGraph;
_resourceTypePublicName = resourceTypePublicName;
}

public void Apply(ApplicationModel application)
{
throw new NotImplementedException();
}

public ResourceType? GetResourceTypeForController(Type? controllerType)
{
return _resourceTypePublicName != null ? _resourceGraph.FindResourceType(_resourceTypePublicName) : null;
}

public string GetControllerNameForResourceType(ResourceType? resourceType)
{
throw new NotImplementedException();
}
}
}
1 change: 0 additions & 1 deletion test/UnitTests/UnitTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,5 @@
<PackageReference Include="GitHubActionsTestLogger" Version="$(GitHubActionsTestLoggerVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="$(EFCoreVersion)" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(TestSdkVersion)" />
<PackageReference Include="Moq" Version="$(MoqVersion)" />
</ItemGroup>
</Project>

0 comments on commit 9e4e9c8

Please sign in to comment.