Mock IHttpContextAccessor for local testing [duplicate] - c#

I have a method to get header value using IHttpContextAccessor
public class HeaderConfiguration : IHeaderConfiguration
{
public HeaderConfiguration()
{
}
public string GetTenantId(IHttpContextAccessor httpContextAccessor)
{
return httpContextAccessor.HttpContext.Request.Headers["Tenant-ID"].ToString();
}
}
I am testing GetBookByBookId method
Let's say the method looks like this:
public class Book
{
private readonly IHttpContextAccessor _httpContextAccessor;
private IHeaderConfiguration _headerConfiguration;
private string _tenantID;
public Book(IHeaderConfiguration headerConfiguration, IHttpContextAccessor httpContextAccessor){
var headerConfig = new HeaderConfiguration();
_httpContextAccessor = httpContextAccessor;
_tenantID = headerConfig.GetTenantId(_httpContextAccessor);
}
public Task<List<BookModel>> GetBookByBookId(string id){
//do something with the _tenantId
//...
}
}
Here's my unit test for GetBookByBookId method
[Fact]
public void test_GetBookByBookId()
{
//Arrange
//Mock IHttpContextAccessor
var mockHttpContextAccessor = new Mock<IHttpContextAccessor>();
mockHttpContextAccessor.Setup(req => req.HttpContext.Request.Headers["Tenant-ID"].ToString()).Returns(It.IsAny<string>());
//Mock HeaderConfiguration
var mockHeaderConfiguration = new Mock<IHeaderConfiguration>();
mockHeaderConfiguration.Setup(x => x.GetTenantId(mockHttpContextAccessor.Object)).Returns(It.IsAny<string>());
var book = new Book( mockHttpContextAccessor.Object, mockHeaderConfiguration.Object);
var bookId = "100";
//Act
var result = book.GetBookByBookId(bookId);
//Assert
result.Result.Should().NotBeNull().And.
BeOfType<List<BookModel>>();
}
But for this line:
mockHttpContextAccessor.Setup(req => req.HttpContext.Request.Headers["Tenant-ID"].ToString()).Returns(It.IsAny<string>());
It says
System.NotSupportedException: 'Type to mock must be an interface or an abstract or non-sealed class. '
I was wondering what's the proper way to mock IHttpContextAccessor with header value?

You can use the DefaultHttpContext as a backing for the IHttpContextAccessor.HttpContext. Saves you having to set-up too many things
Next you cannot use It.IsAny<string>() as a Returns result. They were meant to be used in the set up expressions alone.
Check the refactor
[Fact]
public async Task test_GetBookByBookId() {
//Arrange
//Mock IHttpContextAccessor
var mockHttpContextAccessor = new Mock<IHttpContextAccessor>();
var context = new DefaultHttpContext();
var fakeTenantId = "abcd";
context.Request.Headers["Tenant-ID"] = fakeTenantId;
mockHttpContextAccessor.Setup(_ => _.HttpContext).Returns(context);
//Mock HeaderConfiguration
var mockHeaderConfiguration = new Mock<IHeaderConfiguration>();
mockHeaderConfiguration
.Setup(_ => _.GetTenantId(It.IsAny<IHttpContextAccessor>()))
.Returns(fakeTenantId);
var book = new Book(mockHttpContextAccessor.Object, mockHeaderConfiguration.Object);
var bookId = "100";
//Act
var result = await book.GetBookByBookId(bookId);
//Assert
result.Should().NotBeNull().And.
BeOfType<List<BookModel>>();
}
There may also be an issue with the Class Under Test as it is manually initializing the HeaderConfiguration when it should actually be explicitly injected.
public Book(IHeaderConfiguration headerConfiguration, IHttpContextAccessor httpContextAccessor) {
_httpContextAccessor = httpContextAccessor;
_tenantID = headerConfiguration.GetTenantId(_httpContextAccessor);
}

In my scenario I had to mock IHttpContextAccessor and access the inner request url bits.
I'm sharing it here because I spent a decent amount of time figuring this out and hopefully it'll help someone.
readonly Mock<IHttpContextAccessor> _HttpContextAccessor =
new Mock<IHttpContextAccessor>(MockBehavior.Strict);
void SetupHttpContextAccessorWithUrl(string currentUrl)
{
var httpContext = new DefaultHttpContext();
setRequestUrl(httpContext.Request, currentUrl);
_HttpContextAccessor
.SetupGet(accessor => accessor.HttpContext)
.Returns(httpContext);
static void setRequestUrl(HttpRequest httpRequest, string url)
{
UriHelper
.FromAbsolute(url, out var scheme, out var host, out var path, out var query,
fragment: out var _);
httpRequest.Scheme = scheme;
httpRequest.Host = host;
httpRequest.Path = path;
httpRequest.QueryString = query;
}
}

If you are making use of the wonderful NSubstitute package for NUnit, you can do this...
var mockHttpAccessor = Substitute.For<IHttpContextAccessor>();
var context = new DefaultHttpContext
{
Connection =
{
Id = Guid.NewGuid().ToString()
}
};
mockHttpAccessor.HttpContext.Returns(context);
// usage...

Related

XUnit unit tests for MassTransit consumer

I am using MassTransit 5.5.5 version and xunit 2.4.1
My consumer looks like this
public class StorageInformationConsumer : IConsumer<CreateStorageInformationSummary>
{
private readonly IBus _serviceBus;
private readonly USIntegrationQueueServiceContext _USIntegrationQueueServiceContext;
public StorageInformationConsumer(IBus serviceBus, USIntegrationQueueServiceContext USIntegrationQueueServiceContext)
{
_serviceBus = serviceBus;
_USIntegrationQueueServiceContext = USIntegrationQueueServiceContext;
}
public async Task Consume(ConsumeContext<CreateStorageInformationSummary> createStorageInformationSummarycontext)
{
//....
}
}
And my Test like this
public class StorageInformationConsumerTest
{
private readonly USIntegrationQueueServiceContext _dbContext;
private readonly Mock<IBus> _serviceBusMock;
private readonly StorageInformationConsumer _storageInformationConsumer;
public StorageInformationConsumerTest()
{
var options = new DbContextOptionsBuilder<USIntegrationQueueServiceContext>()
.UseInMemoryDatabase(databaseName: "InMemoryArticleDatabase")
.Options;
_dbContext = new USIntegrationQueueServiceContext(options);
_serviceBusMock = new Mock<IBus>();
_storageInformationConsumer = new StorageInformationConsumer(_serviceBusMock.Object, _dbContext);
}
[Fact]
public async void ItShouldCreateStorageInformation()
{
var createStorageInformationSummary = new CreateStorageInformationSummary
{
ClaimNumber = "C-1234",
WorkQueueItemId = 1,
StorageInformation = CreateStorageInformation(),
};
//How to consume
}
}
How to consume the CreateStorageInformationSummary message in order to call consumer, following doesn't work
var mockMessage = new Mock<ConsumeContext<CreateStorageInformationSummary>>(createStorageInformationSummary);
await _storageInformationConsumer.Consume(mockMessage.Object);
Since you have not clarified what is actually not working, the most I can provide is how to create the mock context and pass it to the subject method under test.
This is simple enough since ConsumeContext<T> is already an interface
[Fact]
public async Task ItShouldCreateStorageInformation() {
//Arrange
var createStorageInformationSummary = new CreateStorageInformationSummary {
ClaimNumber = "C-1234",
WorkQueueItemId = 1,
StorageInformation = CreateStorageInformation(),
};
//Mock the context
var context = Mock.Of<ConsumeContext<CreateStorageInformationSummary>>(_ =>
_.Message == createStorageInformationSummary);
//Act
await _storageInformationConsumer.Consume(context);
//Assert
//...assert the expected behavior
}
Also take note that the test has been updated to return async Task and not async void
Reference Moq Quickstart

Unit test controller with IConfiguration using Moq and Mock setup returns null

New to Unit Testing web api.
I am writing a Unit test to Test a controller and I have to mock Iconfiguration. The appsettings,json has a section called "AppSettings", I'm trying to mock it.
Also, the mock.setup returns null value in the controller causing it to fail.
Here is my controller:
private readonly ILogger _logger;
private readonly IConfiguration _configuration;
private readonly ICarPairingTable PairingTable;
private readonly ICarDealerSettingsTable DealerSettingsTable;
static AppSettings appSettings = null;
public CarController(IConfiguration configuration, ICarPairingTable carPairingTable, ICarDealerSettingsTable settingsTable)
{
_configuration = configuration;
appSettings = configuration.Get<AppSettingsModel>().AppSettings;
PairingTable = carPairingTable;
DealerSettingsTable = settingsTable;
}
[HttpGet]
public ActionResult Get(string id){
string DealerId ="";
DealerId = PairingTable.GetDealerId(id).Result;
if (string.IsNullOrEmpty(DealerId))
{
result = new ReturnResult
{
status = "Fail",
data = "ID is invalid"
};
return NotFound(result);
}
SettingsInfo info = DealerSettingsTable.GetSettingsInfo(DealerId).Result;
if (info == null)
{
result = new ReturnResult
{
status = "Fail",
data = "Not Found"
};
return NotFound(result);
}
result = new ReturnResult
{
status = "Success",
data = info
};
return Ok(result);
}
Here is my Unit Test:
[Fact]
public void Test1()
{
var mockConfig = new Mock<IConfiguration>();
var configurationSection = new Mock<IConfigurationSection>();
configurationSection.Setup(a => a.Value).Returns("testvalue");
mockConfig.Setup(a => a.GetSection("AppSettings")).Returns(configurationSection.Object);
var mock1 = new Mock<ICarPairingTable>();
mock1.Setup(p => p.GetDealerId("456")).ReturnsAsync("123");
var mock2 = new Mock<ICarDealerSettingsTable>();
SettingsInfo mockSettings = new SettingsInfo()
{
DealerId = "123",
Name="Dealer1"
};
mock2.Setup(p => p.GetSettingsInfo("123")).ReturnsAsync(()=>mockSettings);
CarController controller = new CarController(mockConfig.Object, mock1.Object, mock2.Object);
var result = controller.Get("456");
//Dont know what to assert
}
Wrote unit test, but not sure if my approach is correct, Help will be appreciated.
This is more of a design issue wrapped in an XY problem.
Really should not be injecting IConfiguration. Based on how the configuration is using by the controller what you should have done was register the settings with the service collection in startup
Startup.ConfigureServices
//...
AppSettings appSettings = Configuration.Get<AppSettingsModel>().AppSettings;
services.AddSingleton(appSettings);
//...
and explicitly inject the settings into the controller
//...
private readonly AppSettings appSettings = null;
public CarController(AppSettings appSettings , ICarPairingTable carPairingTable, ICarDealerSettingsTable settingsTable) {
this.appSettings = appSettings;
PairingTable = carPairingTable;
DealerSettingsTable = settingsTable;
}
//...
So now when unit testing the controller in isolation, you can initialize an instance of the desired class and provide when exercising the unit test.
Reference Explicit Dependencies Principle
You also appear to be mixing async-await and blocking calls like .Result.
I sugest you make the action async all the way
[HttpGet]
public async Task<ActionResult> Get(string id){
string DealerId = await PairingTable.GetDealerId(id);
if (string.IsNullOrEmpty(DealerId)) {
var result = new ReturnResult {
status = "Fail",
data = "ID is invalid"
};
return NotFound(result);
}
SettingsInfo info = await DealerSettingsTable.GetSettingsInfo(DealerId);
if (info == null) {
var result = new ReturnResult {
status = "Fail",
data = "Not Found"
};
return NotFound(result);
}
var result = new ReturnResult {
status = "Success",
data = info
};
return Ok(result);
}
Reference Async/Await - Best Practices in Asynchronous Programming
That way the unit test can finally be arranged correctly to verify the expected behavior
[Fact]
public async Task Should_Return_Ok_ReturnRsult() {
//Arrange
var id = "456";
var dealerId = "123";
SettingsInfo expected = new SettingsInfo() {
DealerId = dealerId,
Name="Dealer1"
};
var pairingMock = new Mock<ICarPairingTable>();
pairingMock.Setup(p => p.GetDealerId(id)).ReturnsAsync(dealerId);
var dealerSettingsMock = new Mock<ICarDealerSettingsTable>();
dealerSettingsMock.Setup(p => p.GetSettingsInfo(dealerId)).ReturnsAsync(() => expected);
CarController controller = new CarController(new AppSettings(), pairingMock.Object, dealerSettingsMock.Object);
//Act
var actionResult = await controller.Get(id);
var actual = actionResult as OkObjectResult;
//Assert (using FluentAssertions)
actual.Should().NotBeNull();
actual.Value.Should().BeOfType<ReturnResult>();
var actualResult = actual.Value as ReturnResult;
actualResult.data.Should().BeEquivalentTo(expected);
}

Testing controller with xUnit

I have webapi where it needs to call some other endpoint and get data.
My current code as follows
//http client implementation
public interface IHttpClientFactory
{
HttpClient Create();
}
public class HttpClientFactory : IHttpClientFactory
{
private readonly ApplicationSettings _applicationSettings;
HttpClient _httpClient;
public HttpClientFactory(IOptions<ApplicationSettings> settings)
{
_applicationSettings = settings.Value;
}
public HttpClient Create()
{
if (_httpClient != null)
return _httpClient;
var client = new HttpClient()
{
BaseAddress = new Uri($"{_applicationSettings.BaseUrl}")
};
_httpClient = client;
return _httpClient;
}
}
public interface IGetItemsQuery
{
Task<IEnumerable<T>> Execute<T>(string url);
}
public class GetItemQuery: IGetItemsQuery
{
private readonly IHttpClientFactory _httpClientFactory;
public GetPhotosQuery(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<IEnumerable<T>> Execute<T>(string url)
{
using (var response = await _httpClientFactory.Create().GetAsync($"{url}").ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
var resp = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var items = JArray.Parse(resp);
return items.ToObject<T[]>();
}
}
In my controller part
private readonly IGetItemsQuery _getItemsQuery;
public HomeController(IGetItemsQuery getItemsQuery)
{
_getItemsQuery = getItemsQuery;
}
appsettings
"ApplicationSettings": {
"BaseUrl": "http://someendpoint.com/"
}
Startup
services.Configure<ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));
services.AddScoped<IGetItemsQuery, GetPhotosQuery>();
services.AddScoped<IHttpClientFactory, HttpClientFactory>();
I want to try something like below in my test
[Fact]
public void Test_Index()
{
// Arrange
var itemsQuery = new Mock<IGetItemsQuery>();
var controller = new HomeController(itemsQuery.Object);
// Act
var result = controller.Index();
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
Assert.Null(viewResult.ViewName);
}
This is creating mock IGetItemsQuery but this isn't mocking the actual IHttpClientFactory.
Is there a way to do this
Based on your design with the abstracted dependencies there would be no need to mock a client factory in order to unit test the controller.
As you have done in your test, you mock IGetItemsQuery, but you have not set it up to behave as expected when invoked in the test.
If, for example, the controller method under test look something like this
private readonly IGetItemsQuery getItemsQuery;
public HomeController(IGetItemsQuery getItemsQuery) {
this.getItemsQuery = getItemsQuery;
}
public async Task<IActionResult> Index() {
var url = "....";
var items = await getItemsQuery.Execute<MyItem>(url);
return View(items);
}
Then an isolated unit test for the Index action as the method under test could look something like
[Fact]
public async Task Index_Should_Return_View_With_Items() {
// Arrange
var itemsQuery = new Mock<IGetItemsQuery>();
var items = new MyItem[] {
new MyItem(),
new MyItem()
};
itemsQuery.Setup(_ => _.Execute<MyItem>(It.IsAny<string>()))
.ReturnsAsync(items);
var controller = new HomeController(itemsQuery.Object);
// Act
var result = await controller.Index();
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
Assert.Null(viewResult.ViewName);
}

Mock IHttpContextAccessor in Unit Tests

I have a method to get header value using IHttpContextAccessor
public class HeaderConfiguration : IHeaderConfiguration
{
public HeaderConfiguration()
{
}
public string GetTenantId(IHttpContextAccessor httpContextAccessor)
{
return httpContextAccessor.HttpContext.Request.Headers["Tenant-ID"].ToString();
}
}
I am testing GetBookByBookId method
Let's say the method looks like this:
public class Book
{
private readonly IHttpContextAccessor _httpContextAccessor;
private IHeaderConfiguration _headerConfiguration;
private string _tenantID;
public Book(IHeaderConfiguration headerConfiguration, IHttpContextAccessor httpContextAccessor){
var headerConfig = new HeaderConfiguration();
_httpContextAccessor = httpContextAccessor;
_tenantID = headerConfig.GetTenantId(_httpContextAccessor);
}
public Task<List<BookModel>> GetBookByBookId(string id){
//do something with the _tenantId
//...
}
}
Here's my unit test for GetBookByBookId method
[Fact]
public void test_GetBookByBookId()
{
//Arrange
//Mock IHttpContextAccessor
var mockHttpContextAccessor = new Mock<IHttpContextAccessor>();
mockHttpContextAccessor.Setup(req => req.HttpContext.Request.Headers["Tenant-ID"].ToString()).Returns(It.IsAny<string>());
//Mock HeaderConfiguration
var mockHeaderConfiguration = new Mock<IHeaderConfiguration>();
mockHeaderConfiguration.Setup(x => x.GetTenantId(mockHttpContextAccessor.Object)).Returns(It.IsAny<string>());
var book = new Book( mockHttpContextAccessor.Object, mockHeaderConfiguration.Object);
var bookId = "100";
//Act
var result = book.GetBookByBookId(bookId);
//Assert
result.Result.Should().NotBeNull().And.
BeOfType<List<BookModel>>();
}
But for this line:
mockHttpContextAccessor.Setup(req => req.HttpContext.Request.Headers["Tenant-ID"].ToString()).Returns(It.IsAny<string>());
It says
System.NotSupportedException: 'Type to mock must be an interface or an abstract or non-sealed class. '
I was wondering what's the proper way to mock IHttpContextAccessor with header value?
You can use the DefaultHttpContext as a backing for the IHttpContextAccessor.HttpContext. Saves you having to set-up too many things
Next you cannot use It.IsAny<string>() as a Returns result. They were meant to be used in the set up expressions alone.
Check the refactor
[Fact]
public async Task test_GetBookByBookId() {
//Arrange
//Mock IHttpContextAccessor
var mockHttpContextAccessor = new Mock<IHttpContextAccessor>();
var context = new DefaultHttpContext();
var fakeTenantId = "abcd";
context.Request.Headers["Tenant-ID"] = fakeTenantId;
mockHttpContextAccessor.Setup(_ => _.HttpContext).Returns(context);
//Mock HeaderConfiguration
var mockHeaderConfiguration = new Mock<IHeaderConfiguration>();
mockHeaderConfiguration
.Setup(_ => _.GetTenantId(It.IsAny<IHttpContextAccessor>()))
.Returns(fakeTenantId);
var book = new Book(mockHttpContextAccessor.Object, mockHeaderConfiguration.Object);
var bookId = "100";
//Act
var result = await book.GetBookByBookId(bookId);
//Assert
result.Should().NotBeNull().And.
BeOfType<List<BookModel>>();
}
There may also be an issue with the Class Under Test as it is manually initializing the HeaderConfiguration when it should actually be explicitly injected.
public Book(IHeaderConfiguration headerConfiguration, IHttpContextAccessor httpContextAccessor) {
_httpContextAccessor = httpContextAccessor;
_tenantID = headerConfiguration.GetTenantId(_httpContextAccessor);
}
In my scenario I had to mock IHttpContextAccessor and access the inner request url bits.
I'm sharing it here because I spent a decent amount of time figuring this out and hopefully it'll help someone.
readonly Mock<IHttpContextAccessor> _HttpContextAccessor =
new Mock<IHttpContextAccessor>(MockBehavior.Strict);
void SetupHttpContextAccessorWithUrl(string currentUrl)
{
var httpContext = new DefaultHttpContext();
setRequestUrl(httpContext.Request, currentUrl);
_HttpContextAccessor
.SetupGet(accessor => accessor.HttpContext)
.Returns(httpContext);
static void setRequestUrl(HttpRequest httpRequest, string url)
{
UriHelper
.FromAbsolute(url, out var scheme, out var host, out var path, out var query,
fragment: out var _);
httpRequest.Scheme = scheme;
httpRequest.Host = host;
httpRequest.Path = path;
httpRequest.QueryString = query;
}
}
If you are making use of the wonderful NSubstitute package for NUnit, you can do this...
var mockHttpAccessor = Substitute.For<IHttpContextAccessor>();
var context = new DefaultHttpContext
{
Connection =
{
Id = Guid.NewGuid().ToString()
}
};
mockHttpAccessor.HttpContext.Returns(context);
// usage...

How to mock UserManager in .Net Core testing?

I have following code. Im trying to running a test case for create user.Following is what i have tried so far.
public class CreateUserCommandHandlerTest
{
private Mock<UserManager<ApplicationUser>> _userManager;
private CreateUserCommandHandler _systemUnderTest;
public CreateUserCommandHandlerTest()
{
_userManager = MockUserManager.GetUserManager<ApplicationUser>();
var user = new ApplicationUser() { UserName = "ancon1", Email = "ancon#mail.com", RoleType = RoleTypes.Anonymous };
_userManager
.Setup(u => u.CreateAsync(user, "ancon2")).ReturnsAsync(IdentityResult.Success);
_systemUnderTest = new CreateUserCommandHandler(_userManager.Object);
}
[Fact]
public async void Handle_GivenValidInput_ReturnsCreatedResponse()
{
var command = new CreateUserCommand { Username = "ancon1", Email = "ancon#mail.com", Password = "ancon2", RoleType = RoleTypes.Anonymous };
var result = await _systemUnderTest.Handle(command, default(CancellationToken));
Assert.NotNull(result);
Assert.IsType<Application.Commands.CreatedResponse>(result);
}
}
My User manager is here:
public static class MockUserManager
{
public static Mock<UserManager<TUser>> GetUserManager<TUser>()
where TUser : class
{
var store = new Mock<IUserStore<TUser>>();
var passwordHasher = new Mock<IPasswordHasher<TUser>>();
IList<IUserValidator<TUser>> userValidators = new List<IUserValidator<TUser>>
{
new UserValidator<TUser>()
};
IList<IPasswordValidator<TUser>> passwordValidators = new List<IPasswordValidator<TUser>>
{
new PasswordValidator<TUser>()
};
userValidators.Add(new UserValidator<TUser>());
passwordValidators.Add(new PasswordValidator<TUser>());
var userManager = new Mock<UserManager<TUser>>(store.Object, null, passwordHasher.Object, userValidators, passwordValidators, null, null, null, null);
return userManager;
}
}
and my Command handler is this:
public class CreateUserCommandHandler : IRequestHandler<CreateUserCommand, BaseCommandResponse>
{
private readonly UserManager<ApplicationUser> _userManager;
public CreateUserCommandHandler(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<BaseCommandResponse> Handle(CreateUserCommand createUserCommand, CancellationToken cancellationToken)
{
var user = new ApplicationUser { UserName = createUserCommand.Username, Email = createUserCommand.Email, RoleType = createUserCommand.RoleType };
var result = await _userManager.CreateAsync(user, createUserCommand.Password);
if (result.Succeeded)
{
return new CreatedResponse();
}
ErrorResponse errorResponse = new ErrorResponse(result.Errors.Select(e => e.Description).First());
return errorResponse;
}
}
when i'm running my test it fails and saying Object reference not set to an instant of an object.
What am i doing wrong here??
I know this is months old but I keep getting back to this thread. I will extend my own answer on this topic because just pointing to Haok's GitHub example is like saying: "Read a book" as it is huge. It does not pinpoint the issue and what you need to do. You need to isolate a Mock object, but not only that but also you need to 'Setup' the method for 'CreateAsync'. So let's put this in three parts:
You need to MOCK if you are using MOQ or a similar framework to make a mocked up creation of the UserManager.
You need to Setup the methods of UserManager you expect to get results back from.
Optionally you would want to inject some generic list from a mocked Entity Framework Core 2.1 or similar so that you can actually see that a list of IDentity Users actually increases or decreases. Not just that UserManager succeeded and nothing else
So say I have a helper method for returning a Mocked UserManager. Which is just slightly altered from the Haok code:
public static Mock<UserManager<TUser>> MockUserManager<TUser>(List<TUser> ls) where TUser : class
{
var store = new Mock<IUserStore<TUser>>();
var mgr = new Mock<UserManager<TUser>>(store.Object, null, null, null, null, null, null, null, null);
mgr.Object.UserValidators.Add(new UserValidator<TUser>());
mgr.Object.PasswordValidators.Add(new PasswordValidator<TUser>());
mgr.Setup(x => x.DeleteAsync(It.IsAny<TUser>())).ReturnsAsync(IdentityResult.Success);
mgr.Setup(x => x.CreateAsync(It.IsAny<TUser>(), It.IsAny<string>())).ReturnsAsync(IdentityResult.Success).Callback<TUser, string>((x, y) => ls.Add(x));
mgr.Setup(x => x.UpdateAsync(It.IsAny<TUser>())).ReturnsAsync(IdentityResult.Success);
return mgr;
}
What is key to this is I am injecting a generic 'TUser' that is what I will be testing as well injecting a list of this. Similar to my example of:
private List<ApplicationUser> _users = new List<ApplicationUser>
{
new ApplicationUser("User1", "user1#bv.com") { Id = 1 },
new ApplicationUser("User2", "user2#bv.com") { Id = 2 }
};
...
private _userManager = MockUserManager<ApplicationUser>(_users).Object;
Then finally I am testing a pattern with a repository similar to this implementation I want to test:
public async Task<int> CreateUser(ApplicationUser user, string password) => (await _userManager.CreateAsync(user, password)).Succeeded ? user.Id : -1;
I test it like this:
[Fact]
public async Task CreateAUser()
{
var newUser = new ApplicationUser("NewUser", "New#test.com");
var password = "P#ssw0rd!";
var result = await CreateUser(newUser, password);
Assert.Equal(3, _users.Count);
}
The key to what I did is that not only did I 'Setup' the CreateAsync but I provided a callback so I can actually see my list I inject get incremented. Hope this helps someone.
aspnet/Identity is opensource so what you can do is see how they mock it themselves.
Here's how they do it: MockHelpers.cs
TestUserManager
public static UserManager<TUser> TestUserManager<TUser>(IUserStore<TUser> store = null) where TUser : class
{
store = store ?? new Mock<IUserStore<TUser>>().Object;
var options = new Mock<IOptions<IdentityOptions>>();
var idOptions = new IdentityOptions();
idOptions.Lockout.AllowedForNewUsers = false;
options.Setup(o => o.Value).Returns(idOptions);
var userValidators = new List<IUserValidator<TUser>>();
var validator = new Mock<IUserValidator<TUser>>();
userValidators.Add(validator.Object);
var pwdValidators = new List<PasswordValidator<TUser>>();
pwdValidators.Add(new PasswordValidator<TUser>());
var userManager = new UserManager<TUser>(store, options.Object, new PasswordHasher<TUser>(),
userValidators, pwdValidators, new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(), null,
new Mock<ILogger<UserManager<TUser>>>().Object);
validator.Setup(v => v.ValidateAsync(userManager, It.IsAny<TUser>()))
.Returns(Task.FromResult(IdentityResult.Success)).Verifiable();
return userManager;
}
In .NetCore 2.2 you have to do it slightly different. Treat it like an update to #Nick Chapsas answer.
First of all, you have to use IUserPasswordStore instead of IUserStore. IUserPasswordStore inherits IUserStore, but UserManager would like to get IUserPasswordStore. In other way, some things won't work.
If you want to test real behaviour of UserManager (for example CreateUserAsync), you can use real implementations of UserValidator and PasswordValidator. You may want to just to be sure that your method reacts how it supposed to for CreateUser errors.
This is my updated example:
UserManager<TUser> CreateUserManager() where TUser : class
{
Mock<IUserPasswordStore<TUser>> userPasswordStore = new Mock<IUserPasswordStore<TUser>>();
userPasswordStore.Setup(s => s.CreateAsync(It.IsAny<TUser>(), It.IsAny<CancellationToken>()))
.Returns(Task.FromResult(IdentityResult.Success));
var options = new Mock<IOptions<IdentityOptions>>();
var idOptions = new IdentityOptions();
//this should be keep in sync with settings in ConfigureIdentity in WebApi -> Startup.cs
idOptions.Lockout.AllowedForNewUsers = false;
idOptions.Password.RequireDigit = true;
idOptions.Password.RequireLowercase = true;
idOptions.Password.RequireNonAlphanumeric = true;
idOptions.Password.RequireUppercase = true;
idOptions.Password.RequiredLength = 8;
idOptions.Password.RequiredUniqueChars = 1;
idOptions.SignIn.RequireConfirmedEmail = false;
// Lockout settings.
idOptions.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
idOptions.Lockout.MaxFailedAccessAttempts = 5;
idOptions.Lockout.AllowedForNewUsers = true;
options.Setup(o => o.Value).Returns(idOptions);
var userValidators = new List<IUserValidator<TUser>>();
UserValidator<TUser> validator = new UserValidator<TUser>();
userValidators.Add(validator);
var passValidator = new PasswordValidator<TUser>();
var pwdValidators = new List<IPasswordValidator<TUser>>();
pwdValidators.Add(passValidator);
var userManager = new UserManager<TUser>(userPasswordStore.Object, options.Object, new PasswordHasher<TUser>(),
userValidators, pwdValidators, new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(), null,
new Mock<ILogger<UserManager<TUser>>>().Object);
return userManager;
}
Notice that UserPasswordStore has a method (CreateAsync) that should be mocked if you want to test CreateAsync from UserManager.
Password and Lockout settings are taken from my project. They should be kept in sync with your settings, so that you can test the real thing.
Of course you don't test for example PasswordValidator, but you can test your methods, for example:
//Part of user service
public async Task<IdentityResult> Register(UserDto data)
{
SystemUser user = ConvertDtoToUser(data);
IdentityResult result = userManager.CreateAsync(user, data.Password);
//some more code that is dependent on the result
}

Categories

Resources