matteofabbri / AspNetCore.Identity.Mongo

This is a MongoDB provider for the ASP.NET Core 2 Identity framework
https://matteofabbri.org
MIT License
345 stars 88 forks source link

Unit tests #81

Open vova3211 opened 3 years ago

vova3211 commented 3 years ago

Repository does not have unit tests.

Also test projects are not the best way to test library. They good to be useful examples of library usage.

jtlabs777 commented 1 year ago

Speaking of test, I am unable to do unit or integrated tests on my controllers that use Idenitty Mongo as a dependency. Is there a way to mock Identity Mongo RolesManager and UserManagers classes? Or is there a away to spin up test containers on random ports and feed that port to Identity Mongo's connection string? Please advise.

dave0292 commented 10 months ago

I'm having the same problem. I did it this way with no success:

_config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json")
    .SetBasePath(Directory.GetCurrentDirectory())
    .Build();

MongoDbConfig mongoDbSettings = _config.GetSection(nameof(MongoDbConfig)).Get<MongoDbConfig>();

client = new MongoClient(mongoDbSettings.ConnectionString);
var database = client.GetDatabase("MyDb");

IMongoCollection<AppUser> userCollection = database.GetCollection<AppUser>("Users");
IMongoCollection<AppRole> roleCollection = database.GetCollection<AppRole>("Roles");

IdentityErrorDescriber error = new IdentityErrorDescriber();
userStore = new UserStore<AppUser, AppRole, Guid>(userCollection, roleCollection, error);

userManager = new UserManager<AppUser>(userStore, null, null, null, null, null, null, null, null);

signInManager = new SignInManager<AppUser>(
    userManager, Mock.Of<IHttpContextAccessor>(), Mock.Of<IUserClaimsPrincipalFactory<AppUser>>(), null, null, null, null);

//Create user unit test method
bool success = false;

AppUser user = Activator.CreateInstance<AppUser>();
user.UserName = "user1";
user.Email = "user1@test.com";

IdentityResult result = userManager.CreateAsync(user, "Password2023?").Result;

if(result == null)
{
    Assert.Fail("Error creating user user1");
}

But I receive a null result on the "CreateAsync" method. I thought that this was the way to make the userStore to point to the mongoDb, but I´m not sure if it is the correct way.

Anyone has the same issue?

teneko commented 2 weeks ago

Have you considered to use Mongo2Go? A library that starts a MongoDB instance for integration tests. I already use it with success.