Unit Test IdentityDbContext - asp.net

I´ve read that the new EF7 allows in memory storage that makes easier the unit testing. This works great on a DbContext, but the problem that I have so far is that I'm using a IdentityDbContext, which doesn´t come with that option, or I haven't found it so far.
What I'm trying to do is to add unit test to my AccountController which depends on the new UserManager and SignInManager classes. I would like to test against an In-Memory list but I still don´t know how to make those clases use a dbcontext different than the EF-SQL IdentityDbContext. Is there any way around this?

Dec. 27th 2015 - Update for RC1
The project.json
{
"version": "1.0.0-*",
"dependencies": {
"{assembly under test}": "",
"Microsoft.AspNet.Hosting": "1.0.0-*",
"xunit": "2.1.0",
"xunit.runner.dnx": "2.1.0-rc1-*"
},
"commands": {
"test": "xunit.runner.dnx"
},
"frameworks": {
"dnx451": {
"dependencies": {
"Moq": "4.2.1312.1622"
}
}
}
}
A test class sample to test AccountController:
using {Your NS}.Controllers;
using Microsoft.AspNet.Identity;
using Moq;
using Xunit;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.OptionsModel;
using System.Threading;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc.ModelBinding;
using System.Collections.Generic;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.Extensions.Logging;
namespace NS.test.Controllers
{
public class TestRole
{
public string Id { get; private set; }
public string Name { get; set; }
}
public interface ITestUserStore<T>:IUserStore<T>, IUserPasswordStore<T> where T :class
{ }
public class AccountControllerTest
{
private static UserManager<TUser> GetUserManager<TUser>(List<IUserValidator<TUser>> userValidators) where TUser : class
{
var store = new Mock<ITestUserStore<TUser>>();
store.Setup(s => s.CreateAsync(It.IsAny<TUser>(), It.IsAny<CancellationToken>())).ReturnsAsync(IdentityResult.Success);
var options = new Mock<IOptions<IdentityOptions>>();
var idOptions = new IdentityOptions();
idOptions.Lockout.AllowedForNewUsers = false;
options.Setup(o => o.Value).Returns(idOptions);
var pwdValidators = new List<PasswordValidator<TUser>>();
pwdValidators.Add(new PasswordValidator<TUser>());
var userManager = new UserManager<TUser>(store.Object, options.Object, new PasswordHasher<TUser>(),
userValidators, pwdValidators, new UpperInvariantLookupNormalizer(),
new IdentityErrorDescriber(), null,
new Mock<ILogger<UserManager<TUser>>>().Object,
null);
return userManager;
}
private static Mock<SignInManager<TUser>> MockSigninManager<TUser>(UserManager<TUser> userManager) where TUser : class
{
var context = new Mock<HttpContext>();
var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
var roleManager = new RoleManager<TestRole>(new Mock<IRoleStore<TestRole>>().Object,new RoleValidator<TestRole>[] { new RoleValidator<TestRole>() }, null, null, null, null);
var identityOptions = new IdentityOptions();
var options = new Mock<IOptions<IdentityOptions>>();
options.Setup(a => a.Value).Returns(identityOptions);
var claimsFactory = new UserClaimsPrincipalFactory<TUser, TestRole>(userManager, roleManager, options.Object);
return new Mock<SignInManager<TUser>>(userManager, contextAccessor.Object, claimsFactory, options.Object, null);
}
[Fact]
public async Task RegisterTest()
{
var userValidators = new List<IUserValidator<YourUser>>();
var validator = new Mock<IUserValidator<YourUser>>();
userValidators.Add(validator.Object);
var userManager = GetUserManager(userValidators);
validator.Setup(v => v.ValidateAsync(userManager, It.IsAny<ChatLeUser>()))
.Returns(Task.FromResult(IdentityResult.Success)).Verifiable();
var signinManager = MockSigninManager<YourUser>(userManager);
signinManager.Setup(m => m.SignInAsync(It.IsAny<YourUser>(), It.IsAny<bool>(), null)).Returns(Task.FromResult(0)).Verifiable();
var viewData = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary());
using (var controller = new AccountController(userManager, signinManager.Object) { ViewData = viewData })
{
var result = await controller.Register(new RegisterViewModel()
{
ConfirmPassword = "test123",
Password = "Test123-123",
UserName = "test"
});
Assert.IsType<RedirectToActionResult>(result);
}
}
}
}

Ultimately, you'll probably want to mock the UserManager and SignInManager directly. Unfortunately, many of those methods under beta-3 aren't virtual; you'll be a bit stuck there. However, you can see from the source of UserManager and SignInManager that the Identity team appears to be addressing those for the next release.
I personally have several tests not compiling because of the same issue.

Related

How to add Mock db tables in C# test cases

How to create mock db tables for the separate class file in test cases to access the service test case and also I need for that tables between parent and child relation
public static class MockTestData
{
// Test data for the DbSet<User> getter
public static IQueryable<EaepTieriiLangComp> Langcomps
{
get
{ return new List<EaepTieriiLangComp>
{
new EaepTieriiLangComp{EaepAssessmentId=1,LangCompId=1,IsPrimary ="Y",LangId =1,LangReadId=1,LangWrittenId=1,LangSpokenId=1,LangUnderstandId=1 },
new EaepTieriiLangComp{EaepAssessmentId=2,LangCompId=1 ,IsPrimary ="N",LangId =2,LangReadId=2,LangWrittenId=2,LangSpokenId=2,LangUnderstandId=2 }//Lang =obj,LangRead=objRead,LangSpoken =objSpeak,LangWritten=objWrite,LangUnderstand=objUnderstand
}.AsQueryable();
}
}
public static IQueryable<LookupLang> LookupLangs
{
get
{ return new List<LookupLang>
{
new LookupLang{LangId = 1,Description = "lang1",IsActive="Y"},
new LookupLang{LangId = 2,Description = "lang2",IsActive="N"}
}.AsQueryable();
}
}
}`
enter code here`
I tried for the above flow but i didnot get relatons for that tables
If you are using EF Core, you can create inmemory database, add data and make query to it.
Here is example:
First you need install Microsoft.EntityFrameworkCore.InMemory package. After this make options:
_options = new DbContextOptionsBuilder<SomeDbContext>()
.UseInMemoryDatabase(databaseName: "DbTest")
.Options;
using var context = new SomeDbContext(_options);
context.Database.EnsureCreated();
Then add your data:
context.AddRange(
new LookupLang{LangId = 1,Description = "lang1",IsActive="Y"},
new LookupLang{LangId = 2,Description = "lang2",IsActive="N"}
)
And now you can use context for testing purposes
Thank you so much advise to use EF core.InMemory package it is working fine now I followed below code
Inmemory class
using Assessments.TierIIQueryDataModel;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;
namespace AssessmentCommandTest.Helpers
{
public class InMemoryDataProviderQueryService : IDisposable
{
private bool disposedValue = false; // To detect redundant calls
public DbQueryContext CreateContextForInMemory()
{
var option = new DbContextOptionsBuilder<DbQueryContext>().UseInMemoryDatabase(databaseName: "Test_QueryDatabase").Options;
var context = new DbQueryContext(option);
if (context != null)
{
//context.Database.EnsureDeleted();
context.Database.EnsureCreated();
}
return context;
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
}
}
and access to DbQueryContext conext file in my code and write mock tables as below
using AssessmentCommandTest.Helpers;
using Assessments.TierIIQueryDataModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AssessmentCommandTest.MockDbTables
{
public class MockQueryDbContext
{
public TierIIQueryContext MockTierIIQueryContexts()
{
//Create object for Inmemory DB provider
var factory = new InMemoryDataProviderQueryService();
//Get the instance of TierIIQueryContext
var context = factory.CreateContextForInMemory();
context.LookupLang.Add(new LookupLang { LangId = 1, Description = "Arabic", IsActive = "Y" });
context.LookupLang.Add(new LookupLang { LangId = 2, Description = "Bangali", IsActive = "Y" });
context.LookupLang.Add(new LookupLang { LangId = 3, Description = "English", IsActive = "Y" });
context.LookupLang.Add(new LookupLang { LangId = 4, Description = "French", IsActive = "Y" });
enter code here
context.SaveChanges();
return context;
}
}
}

How to pull through Row Version values from a SQLite in-memory database

I am currently implementing a Database collection/fixture for my unit tests, as documented on this question here:
xUnit.net - run code once before and after ALL tests
However, instead of using an InMemory Database, I'm using SQLite as InMemory currently has a bug in .Net Core 2.1 which doesn't do a sequence check when using a byte array type
Which leads me to my current predicament, namely that the byte array when you set up a database fixture doesn't get pulled through to the unit test when the context is pulled from the Database Fixture and into the unit test, which is causing concurrency errors when I try to run the tests.
As an example:
Fist set the DatabaseFixture class like so:
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
var connectionStringbuilder = new SqliteConnectionStringBuilder{DataSource = ":memory:", Cache = SqliteCacheMode.Shared};
var connection = new SqliteConnection(connectionStringbuilder.ToString());
options = new DbContextOptionsBuilder<CRMContext>()
.UseSqlite(connection)
.EnableSensitiveDataLogging()
.Options;
using (var context = new CRMContext(options))
{
context.Database.OpenConnection();
context.Database.EnsureCreated();
context.Persons.AddRange(persons);
context.SaveChanges();
}
}
public DbContextOptions<CRMContext> options { get; set; }
public void Dispose()
{
using (var context = new CRMContext(options))
{
context.Database.CloseConnection();
context.Dispose();
}
}
private IQueryable<Person> persons = new List<Person>()
{
new Person
{
Id = 1,
Forename = "Test",
Surname = "User",
RowVersion = new byte[0]
},
new Person
{
Id = 2,
Forename = "Another",
Surname = "Test",
RowVersion = new byte[0]
}
}.AsQueryable();
}
Setup your empty DatabaseCollection class as per the first link:
[CollectionDefinition("Database collection")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture>
{
}
Then set up your unit test to use this Database Fixture:
[Collection("Database collection")]
public class PersonTests : BaseTests
{
private readonly DatabaseFixture _fixture;
public PersonTests(DatabaseFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void SaveAndReturnEntityAsync_SaveNewPerson_ReturnsTrue()
{
{
using (var context = new Context(_fixture.options))
{
var existingperson = new Person
{
Id = 2,
Forename = "Edit",
Surname = "Test",
RowVersion = new byte[0]
};
var mapperConfig = new MapperConfiguration(cfg => { cfg.AddProfile(new InitializeAutomapperProfile()); });
var AlertAcknowledgeService = GenerateService(context);
//Act
//var result = _Person.SaveAndReturnEntityAsync(mappedPersonAlertAcknowledge);
//Assert
Assert.Equal("RanToCompletion", result.Status.ToString());
Assert.True(result.IsCompletedSuccessfully);
Assert.Equal("The data is saved successfully", result.Result.SuccessMessage);
}
}
Now when I debug this, it hits the fixture correctly, and you can when you expand the Results view, the RowVersion variable is assigned correctly:
However, when the data is passed into the unit test, the row version gets set to null:
Any help on this would be greatly appreciated!

Using RabbitMQ in ASP.net core IHostedService

I am facing a problem that would like help.
I am developing a background process that will be listening to a queue in rabbitmq server.
It is OK if I run it in a .net core console application. However I would like to do it in a more elegant way such as web service (which has given me a lot of trouble where it does not work when installed) or an IIS hosted web application.
I face a problem of Scoped Service when I try to host the service (IHostedService) in .net core web application.
The code below is working fine in a console application. How can make it run as an IHostedService in a .net core web application.
What am I supposed to change.
Your help is appreciated.
CODE:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using PaymentProcessor.Models;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Microsoft.EntityFrameworkCore;
namespace PaymentProcessor
{
public class PaymentProcessingService : HostedService
{
IConfiguration configuration;
private EntitiesContext claimsContext;
private string connectionString;
private string HostName = "";
private string UserName = "";
private string Password = "";
private static int MaxRetries;
private IConnectionFactory factory;
private IConnection connection;
private IModel channel;
public PaymentProcessingService(IConfiguration configuration)
{
this.configuration = configuration;
this.connectionString = configuration.GetConnectionString ("StagingContext");
claimsContext = new EntitiesContext(connectionString);
HostName = this.configuration.GetValue<string>("Settings:HostName");
UserName = this.configuration.GetValue<string>("Settings:UserName");
Password = this.configuration.GetValue<string>("Settings:Password");
MaxRetries = this.configuration.GetValue<string>("Settings:MaxRetries").ConvertTo<int>();
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
connect:
factory = new ConnectionFactory { HostName = HostName, UserName = UserName, Password = Password };
try
{
connection = factory.CreateConnection();
channel = connection.CreateModel();
channel.ExchangeDeclare("payment_rocessing_exchange", "topic");
channel.QueueDeclare("payment_processing_queue", true, false, false, null);
channel.QueueBind("payment_processing_queue", "payment_processing_exchange", "processing");
var queueArgs = new Dictionary<string, object>
{
{ "x-dead-letter-exchange", "payment_processing_exchange" },
{"x-dead-letter-routing-key", "processing_retry"},
{ "x-message-ttl", 10000 }
};
channel.ExchangeDeclare("payment_rocessing_exchange", "topic");
channel.QueueDeclare("payment_processing_retry_queue", true, false, false, queueArgs);
channel.QueueBind("payment_processing_retry_queue", "payment_processing_exchange", "processing_retry", null);
channel.ExchangeDeclare("payment_processing_exchange", "topic");
channel.QueueDeclare("payment_processing_error_queue", true, false, false, null);
channel.QueueBind("payment_processing_error_queue", "payment_processing_exchange", "processing_error", null);
channel.ExchangeDeclare("payment_processing_exchange", "topic");
channel.QueueDeclare("payment_integration_queue", true, false, false, null);
channel.QueueBind("payment_integration_queue", "payment_processing_exchange", "integration", null);
channel.BasicQos(0, 1, false);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var message = ea.Body.DeSerializeText();
try
{
var saveBundle = JObject.Parse(message);
var msg = (dynamic)((dynamic)saveBundle).Message;
string referenceNo = (string)msg.ReferenceNo;
var parameters = new[]
{
new SqlParameter
{
DbType = DbType.String,
ParameterName = "ReferenceNo",
Value =referenceNo
}
};
var result = claimsContext.Database.ExecuteSqlCommand("dbo.PaymentReferencesProcessSingle #ReferenceNo", parameters);
IBasicProperties props = channel.CreateBasicProperties();
props.Persistent = true;
props.ContentType = "text/plain";
props.DeliveryMode = 2;
channel.BasicPublish("payment_processing_exchange", "integration", props, (new MessageEnvelope { RetryCounts = 0, Message = JObject.FromObject(new { ReferenceNo = referenceNo }) }).Serialize());
}
catch (Exception ex)
{
MessageEnvelope envelope = JsonConvert.DeserializeObject<MessageEnvelope>(message);
if (envelope.RetryCounts < MaxRetries)
{
int RetryCounts = envelope.RetryCounts + 1;
MessageEnvelope messageEnvelope = new MessageEnvelope { RetryCounts = RetryCounts, Message = envelope.Message };
var data = messageEnvelope.Serialize();
channel.BasicPublish("payment_processing_exchange", "processing_retry", null, data);
}
else
{
var data = envelope.Serialize();
channel.BasicPublish("payment_processing_exchange", "processing_error", null, data);
}
}
finally
{
channel.BasicAck(ea.DeliveryTag, false);
}
};
channel.BasicConsume(queue: "payment_processing_queue", autoAck: false, consumer: consumer);
}
catch (Exception ex)
{
Thread.Sleep(10000);
goto connect;
}
}
}
}
and then
services.AddScoped<IHostedService, PaymentProcessingService>();
As Dekim mentioned a service should be registered.
Please have a look on an example I created on GitHub.
Program.cs looks like this:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
namespace Core
{
internal class Program
{
static async Task Main(string[] args)
{
await new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<ServiceRabbitMQ>(); // register our service here
})
.RunConsoleAsync();
}
}
}
Because the IHostedService requires the creation of a special scope according to the documentation.
From the Microsoft documentation cited in the above answer :
No scope is created for a hosted service by default.
Consider using : services.AddHostedService<MyHostedService>();

Moq how to test BusinessLayer

I have problem with the Unit Test my Module from Business Layer.
I'm using Moq.
my Module from DL :
namespace EF.BusinessLayer.Modules
{
public class UserModule : IUserModule
{
public User AddUser(User user)
{
using (IUnitOfWork uow = IoC.Resolve<IUnitOfWork>())
{
uow.Add(user);
uow.SaveChanges();
return uow.Queryable<User>().Where(x => x.Username == user.Username).FirstOrDefault();
}
}
}
}
I'm trying to write a test, with which I can test if my entity was added properly.
[TestMethod]
public void AddUserTestMethod()
{
User user = new User()
{
FirstName = "Criss",
LastName = "Johnson",
Username = "CJ",
Email = "email#cj.com"
};
var mockContext = new Mock<IUserModule>();
mockContext.Setup<User>(x => x.AddUser(user)).Callback<User>((c) => User = c);
var result = mockContext.Object.AddUser(user);
}
but results = null.
What I'm doing wrong ?
Lets understand what is your system under test (SUT). From your description, I think it's UserModule.
Note that UserModule depends on IUnitOfWork, which you have very rightly dependency injected using an IoC container.
One of the key things of unit testing is to test the SUT in isolation. Which means for testing the business logic under UserModule, you should be mocking the IUnitOfWork. That's the problem I see with your test. It mocks the UserModule itself.
I suggest you to register the mocked IUnitOfWork in your IoC container before calling the "AddUser" method of UserModule.
[TestMethod]
public void AddUserTestMethod()
{
/*given*/
User expectedUser = new User()
{
FirstName = "Criss",
LastName = "Johnson",
Username = "CJ",
Email = "email#cj.com"
};
var users = new List<User>();
users.Add(expectedUser);
//mock IUnitWork
var mockUnitOfWork= new Mock<IUnitOfWork>();
mockUnitOfWork.Setup(x => x.Add(user));
mockUnitOfWork.Setup(x => x.SaveChanges());
//This may not work as is, could need modification
mockUnitOfWork.Setup(x => x.Queryable<User>()).Returns(users);
//Register mocked unit of work in IoC container
IoC.Register<IUnitOfWork>(mockUnitOfWork.Object);
//Instantiate SUT
var userModule = new UserModule();
/*when*/
var result = userModule.AddUser(user);
/*then*/
//Assert here
}

How can i use engine object in my console application

"How can i use engine in my console application"
I shouldn't use the ITemplate-interface and Transform-Method.
I am using Tridion 2011
Could anyone please suggest me.
You can't. The Engine class is part of the TOM.NET and that API is explicitly reserved for use in:
Template Building Blocks
Event Handlers
For all other cases (such as console applications) you should use the Core Service.
There are many good questions (and articles on other web sites) already:
https://stackoverflow.com/search?q=%5Btridion%5D+core+service
http://www.google.com/#q=tridion+core+service
If you get stuck along the way, show us the relevant code+configuration you have and what error message your get (or at what step you are stuck) and we'll try to help from there.
From a console application you should use the Core Service. I wrote a small example using the Core Service to search for items in the content manager.
Console.WriteLine("FullTextQuery:");
var fullTextQuery = Console.ReadLine();
if (String.IsNullOrWhiteSpace(fullTextQuery) || fullTextQuery.Equals(":q", StringComparison.OrdinalIgnoreCase))
{
break;
}
Console.WriteLine("SearchIn IdRef:");
var searchInIdRef = Console.ReadLine();
var queryData = new SearchQueryData
{
FullTextQuery = fullTextQuery,
SearchIn = new LinkToIdentifiableObjectData
{
IdRef = searchInIdRef
}
};
var results = coreServiceClient.GetSearchResults(queryData);
results.ToList().ForEach(result => Console.WriteLine("{0} ({1})", result.Title, result.Id));
Add a reference to Tridion.ContentManager.CoreService.Client to your Visual Studio Project.
Code of the Core Service Client Provider:
public interface ICoreServiceProvider
{
CoreServiceClient GetCoreServiceClient();
}
public class CoreServiceDefaultProvider : ICoreServiceProvider
{
private CoreServiceClient _client;
public CoreServiceClient GetCoreServiceClient()
{
return _client ?? (_client = new CoreServiceClient());
}
}
And the client itself:
public class CoreServiceClient : IDisposable
{
public SessionAwareCoreServiceClient ProxyClient;
private const string DefaultEndpointName = "netTcp_2011";
public CoreServiceClient(string endPointName)
{
if(string.IsNullOrWhiteSpace(endPointName))
{
throw new ArgumentNullException("endPointName", "EndPointName is not specified.");
}
ProxyClient = new SessionAwareCoreServiceClient(endPointName);
}
public CoreServiceClient() : this(DefaultEndpointName) { }
public string GetApiVersionNumber()
{
return ProxyClient.GetApiVersion();
}
public IdentifiableObjectData[] GetSearchResults(SearchQueryData filter)
{
return ProxyClient.GetSearchResults(filter);
}
public IdentifiableObjectData Read(string id)
{
return ProxyClient.Read(id, new ReadOptions());
}
public ApplicationData ReadApplicationData(string subjectId, string applicationId)
{
return ProxyClient.ReadApplicationData(subjectId, applicationId);
}
public void Dispose()
{
if (ProxyClient.State == CommunicationState.Faulted)
{
ProxyClient.Abort();
}
else
{
ProxyClient.Close();
}
}
}
When you want to perform CRUD actions through the core service you can implement the following methods in the client:
public IdentifiableObjectData CreateItem(IdentifiableObjectData data)
{
data = ProxyClient.Create(data, new ReadOptions());
return data;
}
public IdentifiableObjectData UpdateItem(IdentifiableObjectData data)
{
data = ProxyClient.Update(data, new ReadOptions());
return data;
}
public IdentifiableObjectData ReadItem(string id)
{
return ProxyClient.Read(id, new ReadOptions());
}
To construct a data object of e.g. a Component you can implement a Component Builder class that implements a create method that does this for you:
public ComponentData Create(string folderUri, string title, string content)
{
var data = new ComponentData()
{
Id = "tcm:0-0-0",
Title = title,
Content = content,
LocationInfo = new LocationInfo()
};
data.LocationInfo.OrganizationalItem = new LinkToOrganizationalItemData
{
IdRef = folderUri
};
using (CoreServiceClient client = provider.GetCoreServiceClient())
{
data = (ComponentData)client.CreateItem(data);
}
return data;
}
Hope this gets you started.

Resources