简体   繁体   中英

How to make a net core library with usermanager functions

Once again i stumbled across a problem. Well its not realy a problem, its more a thing that i want to learn. I want to start learning class libraries for .net core. First of i created a class library project with the right settings. Now i want to create functions which use for example

applicationusermanager

I have no idea how to access the applicationusermanager from my other project. While i was reading some posts i saw that it has something to do with dependencies. Once again, i dont have a clue if its even possible or how should start.

Lets for example say that i have a library function like this:

public static async Task<ApplicationUser> Get_User_Test()
    {
        return await _usermanager.FindByEmailAsync("test@test.com");
    }

I want this function to run in my main project. I call this by doing library.Get_User_Test();but it fails.

Some good articles or suggestions would be appreciated. I just simply dont know where to start.

I hope you are all doing good and are healthy. Thanks for reading this and i whish you a good day.

Kind regards,

Nick

UserManager provides the APIs for managing user in a persistence store . It is a bare bone of ASP.NET Core Identity to provide all authentication/authorization logic when you work with .NET Core. It is a cross-cutting logic so you don't want to test itself. The only thing you perform Unit Test is your custom IUserStore when you choose to integrate Database without Entity Framework Core here .

You can imagine UserManager will call each implemented method in your implemented IUserStore class. Because it is your custom code, so you should write UT for this.

There is a sample code.

public class MongoUserStore : IUserStore<ApplicationUser>
{
    private readonly IUserRepository _userRepo;
    public MongoUserStore(IUserRepository userRepo)
    {
        _userRepo = userRepo;
    }

    public async Task<User> FindByIdAsync(string userId, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var user = await _userRepo.GetOneAsync(userId);
            if (user != null)
            {
                return user;
            }

            return null;
        }
}

Then you need to write UT for this class

public class Test
{
    [Fact]
    public async Task Find_By_Id_Test()
    {
        // Arrange
        // Your mock here
        var mockMongoUserStore = Mock<IUserStore<ApplicationUser>>();
        // Act
        var user = await mockMongoUserStore.FindByIdAsync("abc", null);
        // Assert
        Assert.True(user != null);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM