Open vova3211 opened 3 years 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.
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?
Have you considered to use Mongo2Go? A library that starts a MongoDB instance for integration tests. I already use it with success.
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.