Skip to content

Commit

Permalink
Merge pull request #13 from Lombiq/issue/OSOE-60
Browse files Browse the repository at this point in the history
OSOE-60: .NET 6 and Orchard Core 1.3 upgrade
  • Loading branch information
sarahelsaig authored Mar 17, 2022
2 parents 8ae669c + 40c746a commit 97404ae
Show file tree
Hide file tree
Showing 4 changed files with 156 additions and 159 deletions.
33 changes: 16 additions & 17 deletions Extensions/AutoMockerExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
using Microsoft.Extensions.Localization;
using System.Collections.Generic;

namespace Moq.AutoMock
namespace Moq.AutoMock;

public static class AutoMockerExtensions
{
public static class AutoMockerExtensions
{
/// <summary>
/// Register zero or more services with <see cref="AutoMocker.Use{TService}(TService)"/> as <see
/// cref="IEnumerable{TService}"/>. This is to simulate the DI feature where you can inject all implementations
/// of a given service as <see cref="IEnumerable{TService}"/>.
/// </summary>
/// <param name="mocker">The <see cref="AutoMocker"/> performing the registration.</param>
/// <param name="objects">The collection of instances to be registered.</param>
/// <typeparam name="T">The service type.</typeparam>
public static void Some<T>(this AutoMocker mocker, params T[] objects) => mocker.Use<IEnumerable<T>>(objects);
/// <summary>
/// Register zero or more services with <see cref="AutoMocker.Use{TService}(TService)"/> as <see
/// cref="IEnumerable{TService}"/>. This is to simulate the DI feature where you can inject all implementations of a
/// given service as <see cref="IEnumerable{TService}"/>.
/// </summary>
/// <param name="mocker">The <see cref="AutoMocker"/> performing the registration.</param>
/// <param name="objects">The collection of instances to be registered.</param>
/// <typeparam name="T">The service type.</typeparam>
public static void Some<T>(this AutoMocker mocker, params T[] objects) => mocker.Use<IEnumerable<T>>(objects);

public static void MockStringLocalizer<T>(this AutoMocker mocker) =>
mocker.GetMock<IStringLocalizer<T>>()
.Setup(localizer => localizer[It.IsAny<string>()])
.Returns<string>(parameter => new LocalizedString(parameter, parameter));
}
public static void MockStringLocalizer<T>(this AutoMocker mocker) =>
mocker.GetMock<IStringLocalizer<T>>()
.Setup(localizer => localizer[It.IsAny<string>()])
.Returns<string>(parameter => new LocalizedString(parameter, parameter));
}
137 changes: 68 additions & 69 deletions Helpers/MockHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,80 +7,79 @@
using System.Collections.Generic;
using System.Security.Claims;

namespace Lombiq.Tests.Helpers
namespace Lombiq.Tests.Helpers;

public static class MockHelper
{
public static class MockHelper
{
public static ControllerContext CreateMockControllerContextWithUser() =>
new()
{
HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal() },
};
public static ControllerContext CreateMockControllerContextWithUser() =>
new()
{
HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal() },
};

[Obsolete("Use the correctly named ConfigureMockAuthorizationService() instead.")]
public static void ConfigureMockAutherizationService(this AutoMocker mocker, AuthorizationResult authorizationResult) =>
ConfigureMockAuthorizationService(mocker, authorizationResult);
[Obsolete("Use the correctly named ConfigureMockAuthorizationService() instead.")]
public static void ConfigureMockAutherizationService(this AutoMocker mocker, AuthorizationResult authorizationResult) =>
ConfigureMockAuthorizationService(mocker, authorizationResult);

public static void ConfigureMockAuthorizationService(this AutoMocker mocker, AuthorizationResult authorizationResult) =>
mocker
.GetMock<IAuthorizationService>()
.Setup(authorizationService => authorizationService.AuthorizeAsync(
It.IsAny<ClaimsPrincipal>(),
It.IsAny<object>(),
It.IsAny<IEnumerable<IAuthorizationRequirement>>()))
.ReturnsAsync(authorizationResult);
public static void ConfigureMockAuthorizationService(this AutoMocker mocker, AuthorizationResult authorizationResult) =>
mocker
.GetMock<IAuthorizationService>()
.Setup(authorizationService => authorizationService.AuthorizeAsync(
It.IsAny<ClaimsPrincipal>(),
It.IsAny<object>(),
It.IsAny<IEnumerable<IAuthorizationRequirement>>()))
.ReturnsAsync(authorizationResult);

/// <summary>
/// Creates an <see cref="AutoMocker"/> and resolves an instance of <typeparamref name="T"/> from it.
/// </summary>
/// <typeparam name="T">The type to resolve.</typeparam>
/// <param name="configurator">
/// Delegate to apply configuration to the <see cref="AutoMocker"/> instance. Optional, defaults to
/// <see langword="null"/>.
/// </param>
/// <param name="enablePrivate">
/// When <see langword="true"/>, non-public constructors will also be used to create mocks. Optional, defaults
/// to <see langword="false"/>.
/// </param>
public static T CreateAutoMockerInstance<T>(Action<AutoMocker> configurator = null, bool enablePrivate = false)
where T : class =>
CreateAutoMockerInstance<T>(configurator, enablePrivate, out _);
/// <summary>
/// Creates an <see cref="AutoMocker"/> and resolves an instance of <typeparamref name="T"/> from it.
/// </summary>
/// <typeparam name="T">The type to resolve.</typeparam>
/// <param name="configurator">
/// Delegate to apply configuration to the <see cref="AutoMocker"/> instance. Optional, defaults to <see
/// langword="null"/>.
/// </param>
/// <param name="enablePrivate">
/// When <see langword="true"/>, non-public constructors will also be used to create mocks. Optional, defaults to
/// <see langword="false"/>.
/// </param>
public static T CreateAutoMockerInstance<T>(Action<AutoMocker> configurator = null, bool enablePrivate = false)
where T : class =>
CreateAutoMockerInstance<T>(configurator, enablePrivate, out _);

/// <summary>
/// Creates an <see cref="AutoMocker"/> and resolves an instance of <typeparamref name="T"/> from it.
/// </summary>
/// <typeparam name="T">The type to resolve.</typeparam>
/// <param name="mocker">The newly created <see cref="AutoMocker"/> instance.</param>
/// <param name="enablePrivate">
/// When <see langword="true"/>, non-public constructors will also be used to create mocks. Optional, defaults
/// to <see langword="false"/>.
/// </param>
public static T CreateAutoMockerInstance<T>(out AutoMocker mocker, bool enablePrivate = false)
where T : class =>
CreateAutoMockerInstance<T>(configurator: null, enablePrivate, out mocker);
/// <summary>
/// Creates an <see cref="AutoMocker"/> and resolves an instance of <typeparamref name="T"/> from it.
/// </summary>
/// <typeparam name="T">The type to resolve.</typeparam>
/// <param name="mocker">The newly created <see cref="AutoMocker"/> instance.</param>
/// <param name="enablePrivate">
/// When <see langword="true"/>, non-public constructors will also be used to create mocks. Optional, defaults to
/// <see langword="false"/>.
/// </param>
public static T CreateAutoMockerInstance<T>(out AutoMocker mocker, bool enablePrivate = false)
where T : class =>
CreateAutoMockerInstance<T>(configurator: null, enablePrivate, out mocker);

/// <summary>
/// Creates an <see cref="AutoMocker"/> and resolves an instance of <typeparamref name="T"/> from it.
/// </summary>
/// <remarks>
/// <para>
/// Note that configurator is also needed because if you want control on what exactly will be injected into the
/// created instance you'll need to set that up before instantiation. Then the AutoMocker instance needs to be
/// available afterwards too, at least for verification.
/// </para>
/// </remarks>
/// <typeparam name="T">The type to resolve.</typeparam>
/// <param name="configurator">Delegate to apply configuration to the <see cref="AutoMocker"/> instance.</param>
/// <param name="mocker">The newly created <see cref="AutoMocker"/> instance.</param>
/// <param name="enablePrivate">
/// When <see langword="true"/>, non-public constructors will also be used to create mocks.
/// </param>
public static T CreateAutoMockerInstance<T>(Action<AutoMocker> configurator, bool enablePrivate, out AutoMocker mocker)
where T : class
{
mocker = new AutoMocker();
configurator?.Invoke(mocker);
return mocker.CreateInstance<T>(enablePrivate);
}
/// <summary>
/// Creates an <see cref="AutoMocker"/> and resolves an instance of <typeparamref name="T"/> from it.
/// </summary>
/// <remarks>
/// <para>
/// Note that configurator is also needed because if you want control on what exactly will be injected into the
/// created instance you'll need to set that up before instantiation. Then the AutoMocker instance needs to be
/// available afterwards too, at least for verification.
/// </para>
/// </remarks>
/// <typeparam name="T">The type to resolve.</typeparam>
/// <param name="configurator">Delegate to apply configuration to the <see cref="AutoMocker"/> instance.</param>
/// <param name="mocker">The newly created <see cref="AutoMocker"/> instance.</param>
/// <param name="enablePrivate">
/// When <see langword="true"/>, non-public constructors will also be used to create mocks.
/// </param>
public static T CreateAutoMockerInstance<T>(Action<AutoMocker> configurator, bool enablePrivate, out AutoMocker mocker)
where T : class
{
mocker = new AutoMocker();
configurator?.Invoke(mocker);
return mocker.CreateInstance<T>(enablePrivate);
}
}
135 changes: 67 additions & 68 deletions Helpers/UserManagerMockHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,79 +5,78 @@
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Lombiq.Tests.Helpers
namespace Lombiq.Tests.Helpers;

// Copy-pasted from https://github.com/dotnet/aspnetcore/blob/master/src/Identity/test/Shared/MockHelpers.cs to be able
// to test UserGroupService. Also see:
// https://stackoverflow.com/questions/49165810/how-to-mock-usermanager-in-net-core-testing
public static class UserManagerMockHelpers
{
// Copy-pasted from https://github.com/dotnet/aspnetcore/blob/master/src/Identity/test/Shared/MockHelpers.cs to be
// able to test UserGroupService. Also see:
// https://stackoverflow.com/questions/49165810/how-to-mock-usermanager-in-net-core-testing
public static class UserManagerMockHelpers
public static Mock<UserManager<TUser>> MockUserManager<TUser>()
where TUser : class
{
public static Mock<UserManager<TUser>> MockUserManager<TUser>()
where TUser : class
{
var store = new Mock<IUserStore<TUser>>();
var userManagerMock = new Mock<UserManager<TUser>>(store.Object, null, null, null, null, null, null, null, null);
userManagerMock.Object.UserValidators.Add(new UserValidator<TUser>());
userManagerMock.Object.PasswordValidators.Add(new PasswordValidator<TUser>());
return userManagerMock;
}
var store = new Mock<IUserStore<TUser>>();
var userManagerMock = new Mock<UserManager<TUser>>(store.Object, null, null, null, null, null, null, null, null);
userManagerMock.Object.UserValidators.Add(new UserValidator<TUser>());
userManagerMock.Object.PasswordValidators.Add(new PasswordValidator<TUser>());
return userManagerMock;
}

public static Mock<RoleManager<TRole>> MockRoleManager<TRole>(IRoleStore<TRole> store = null)
where TRole : class
{
store ??= new Mock<IRoleStore<TRole>>().Object;
var roles = new List<IRoleValidator<TRole>> { new RoleValidator<TRole>() };
return new Mock<RoleManager<TRole>>(
store,
roles,
new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(),
null);
}
public static Mock<RoleManager<TRole>> MockRoleManager<TRole>(IRoleStore<TRole> store = null)
where TRole : class
{
store ??= new Mock<IRoleStore<TRole>>().Object;
var roles = new List<IRoleValidator<TRole>> { new RoleValidator<TRole>() };
return new Mock<RoleManager<TRole>>(
store,
roles,
new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(),
null);
}

public static Mock<IOptions<IdentityOptions>> MockIdentityOptions()
{
var options = new Mock<IOptions<IdentityOptions>>();
var idOptions = new IdentityOptions { Lockout = { AllowedForNewUsers = false } };
options.Setup(o => o.Value).Returns(idOptions);
return options;
}
public static Mock<IOptions<IdentityOptions>> MockIdentityOptions()
{
var options = new Mock<IOptions<IdentityOptions>>();
var idOptions = new IdentityOptions { Lockout = { AllowedForNewUsers = false } };
options.Setup(o => o.Value).Returns(idOptions);
return options;
}

public static UserManager<TUser> TestUserManager<TUser>(IUserStore<TUser> store = null)
where TUser : class
{
store ??= new Mock<IUserStore<TUser>>().Object;
var options = MockIdentityOptions();
var userValidators = new List<IUserValidator<TUser>>();
var validator = new Mock<IUserValidator<TUser>>();
userValidators.Add(validator.Object);
var pwdValidators = new List<PasswordValidator<TUser>> { new PasswordValidator<TUser>() };
var userManager = new UserManager<TUser>(
store,
options.Object,
new PasswordHasher<TUser>(),
userValidators,
pwdValidators,
new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(),
services: null,
new Mock<ILogger<UserManager<TUser>>>().Object);
validator.Setup(v => v.ValidateAsync(userManager, It.IsAny<TUser>()))
.Returns(Task.FromResult(IdentityResult.Success)).Verifiable();
return userManager;
}
public static UserManager<TUser> TestUserManager<TUser>(IUserStore<TUser> store = null)
where TUser : class
{
store ??= new Mock<IUserStore<TUser>>().Object;
var options = MockIdentityOptions();
var userValidators = new List<IUserValidator<TUser>>();
var validator = new Mock<IUserValidator<TUser>>();
userValidators.Add(validator.Object);
var pwdValidators = new List<PasswordValidator<TUser>> { new PasswordValidator<TUser>() };
var userManager = new UserManager<TUser>(
store,
options.Object,
new PasswordHasher<TUser>(),
userValidators,
pwdValidators,
new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(),
services: null,
new Mock<ILogger<UserManager<TUser>>>().Object);
validator.Setup(v => v.ValidateAsync(userManager, It.IsAny<TUser>()))
.Returns(Task.FromResult(IdentityResult.Success)).Verifiable();
return userManager;
}

public static RoleManager<TRole> TestRoleManager<TRole>(IRoleStore<TRole> store = null)
where TRole : class
{
store ??= new Mock<IRoleStore<TRole>>().Object;
var roles = new List<IRoleValidator<TRole>> { new RoleValidator<TRole>() };
return new RoleManager<TRole>(
store,
roles,
new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(),
logger: null);
}
public static RoleManager<TRole> TestRoleManager<TRole>(IRoleStore<TRole> store = null)
where TRole : class
{
store ??= new Mock<IRoleStore<TRole>>().Object;
var roles = new List<IRoleValidator<TRole>> { new RoleValidator<TRole>() };
return new RoleManager<TRole>(
store,
roles,
new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(),
logger: null);
}
}
10 changes: 5 additions & 5 deletions Lombiq.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<IsPackable>true</IsPackable>
<DefaultItemExcludes>$(DefaultItemExcludes);.git*</DefaultItemExcludes>
</PropertyGroup>
Expand All @@ -25,12 +25,12 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="3.1.15" />
<PackageReference Include="FluentAssertions" Version="5.10.3" />
<PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.3" />
<PackageReference Include="FluentAssertions" Version="6.5.1" />
<PackageReference Include="Moq" Version="4.17.2" />
<PackageReference Include="Shouldly" Version="4.0.3" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="Moq.AutoMock" Version="2.3.0" />
<PackageReference Include="Moq.AutoMock" Version="3.3.0" />
</ItemGroup>

<!-- These are necessary for symbols NuGet packaging, otherwise Shouldly would prevent PDBs to be packaged, see:
Expand Down

0 comments on commit 97404ae

Please sign in to comment.