簡體   English   中英

.net核心和身份框架的集成測試

[英]integration testing with .net core and identity framework

我只是在任何地方都找不到答案。 我已經閱讀了多篇文章,並查看了許多源代碼,但是似乎都沒有幫助。

http://www.dotnetcurry.com/aspnet-core/1420/integration-testing-aspnet-core

https://www.davepaquette.com/archive/2016/11/27/integration-testing-with-entity-framework-core-and-sql-server.aspx

https://docs.microsoft.com/zh-cn/aspnet/core/testing/integration-testing

我遇到的問題是解決服務,而不是使用HttpClient來測試控制器。 這是我的入門班:

public class Startup: IStartup
{
    protected IServiceProvider _provider;
    private readonly IConfiguration _configuration;
    public Startup(IConfiguration configuration) => _configuration = configuration;

    // This method gets called by the runtime. Use this method to add services to the container.
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.Configure<MvcOptions>(options => options.Filters.Add(new RequireHttpsAttribute()));

        SetUpDataBase(services);
        services.AddMvc();
        services
            .AddIdentityCore<User>(null)
            .AddDefaultTokenProviders();
        return services.BuildServiceProvider();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app)
    {
        var options = new RewriteOptions().AddRedirectToHttps();

        app.UseRewriter(options);
        app.UseAuthentication();
        app.UseMvc();

        using(var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var context = scope.ServiceProvider.GetService<DatabaseContext>();
            EnsureDatabaseCreated(context);
        }
    }

    protected virtual void SetUpDataBase(IServiceCollection services) => services.AddDbContext(_configuration);

    protected virtual void EnsureDatabaseCreated(DatabaseContext dbContext)
    {
        dbContext.Database.Migrate();
    }
}

然后在集成測試中,我創建了2個安裝程序類。 第一個是TestStartup

public class TestStartup: Startup, IDisposable
{

    private const string DatabaseName = "vmpyr";

    public TestStartup(IConfiguration configuration) : base(configuration)
    {
    }

    protected override void EnsureDatabaseCreated(DatabaseContext dbContext)
    {
        DestroyDatabase();
        CreateDatabase();
    }

    protected override void SetUpDataBase(IServiceCollection services)
    {
        var connectionString = Database.ToString();
        var connection = new SqlConnection(connectionString);
        services
            .AddEntityFrameworkSqlServer()
            .AddDbContext<DatabaseContext>(
                options => options.UseSqlServer(connection)
            );
    }

    public void Dispose()
    {
        DestroyDatabase();
    }

    private static void CreateDatabase()
    {
        ExecuteSqlCommand(Master, $@"Create Database [{ DatabaseName }] ON (NAME = '{ DatabaseName }', FILENAME = '{Filename}')");
        var connectionString = Database.ToString();
        var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
        optionsBuilder.UseSqlServer(connectionString);
        using (var context = new DatabaseContext(optionsBuilder.Options))
        {
            context.Database.Migrate();
            DbInitializer.Initialize(context);
        }
    }

    private static void DestroyDatabase()
    {
        var fileNames = ExecuteSqlQuery(Master, $@"SELECT [physical_name] FROM [sys].[master_files] WHERE [database_id] = DB_ID('{ DatabaseName }')", row => (string)row["physical_name"]);
        if (!fileNames.Any()) return;
        ExecuteSqlCommand(Master, $@"ALTER DATABASE [{ DatabaseName }] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; EXEC sp_detach_db '{ DatabaseName }'");
        fileNames.ForEach(File.Delete);
    }

    private static void ExecuteSqlCommand(SqlConnectionStringBuilder connectionStringBuilder, string commandText)
    {
        using (var connection = new SqlConnection(connectionStringBuilder.ConnectionString))
        {
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = commandText;
                command.ExecuteNonQuery();
            }
        }
    }

    private static List<T> ExecuteSqlQuery<T>(SqlConnectionStringBuilder connectionStringBuilder, string queryText, Func<SqlDataReader, T> read)
    {
        var result = new List<T>();
        using (var connection = new SqlConnection(connectionStringBuilder.ConnectionString))
        {
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = queryText;
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        result.Add(read(reader));
                    }
                }
            }
        }
        return result;
    }

    private static SqlConnectionStringBuilder Master => new SqlConnectionStringBuilder
    {
        DataSource = @"(LocalDB)\MSSQLLocalDB",
        InitialCatalog = "master",
        IntegratedSecurity = true
    };

    private static SqlConnectionStringBuilder Database => new SqlConnectionStringBuilder
    {
        DataSource = @"(LocalDB)\MSSQLLocalDB",
        InitialCatalog = DatabaseName,
        IntegratedSecurity = true
    };

    private static string Filename => Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), $"{ DatabaseName }.mdf");
}

這處理了我所有的數據庫創建和服務配置。 第二個是我的TestFixture類:

public class TestFixture<TStartup> : IDisposable where TStartup : class
{
    private readonly IServiceScope _scope;
    private readonly TestServer _testServer;

    public TestFixture()
    {
        var webHostBuilder = new WebHostBuilder().UseStartup<TStartup>();  

        _testServer = new TestServer(webHostBuilder);
        _scope = _testServer.Host.Services.CreateScope();
    }

    public TEntity Resolve<TEntity>() => _scope.ServiceProvider.GetRequiredService<TEntity>();

    public void Dispose()
    {
        _scope.Dispose();
        _testServer.Dispose();
    }
}

如您所見,這將創建測試服務器,但還公開了應解析我的服務的Resolve方法。 現在來我的測試。 我創建了一個UserContext類,如下所示:

public class UserContext
{
    private readonly UserManager<User> _userManager;
    private UserContext(TestFixture<TestStartup> fixture) => _userManager = fixture.Resolve<UserManager<User>>();

    public static UserContext GivenServices() => new UserContext(new TestFixture<TestStartup>());

    public async Task<User> WhenCreateUserAsync(string email)
    {
        var user = new User
        {
            UserName = email,
            Email = email
        };
        var result = await _userManager.CreateAsync(user);
        if (!result.Succeeded)
            throw new Exception(result.Errors.Join(", "));
        return user;
    }

    public async Task<User> WhenGetUserAsync(string username) => await _userManager.FindByNameAsync(username);
}

然后我創建了一個測試:

[TestFixture]
public class UserManagerTests
{

    [Test]
    public async Task ShouldCreateUser()
    {
        var services = UserContext.GivenServices();
        await services.WhenCreateUserAsync("tim@tim.com");
        var user = await services.WhenGetUserAsync("tim@tim.com");
        user.Should().NotBe(null);
    }
}

不幸的是,當我運行測試時錯誤指出:

消息:System.InvalidOperationException: 1[vmpyr.Data.Models.User]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager 1 [vmpyr.Data.Models 1[vmpyr.Data.Models.User]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager無法解析類型為“ Microsoft.AspNetCore.Identity.IUserStore 1[vmpyr.Data.Models.User]' while attempting to activate 'Microsoft.AspNetCore.Identity.UserManager服務。用戶]'。

我認為這告訴我,盡管找到了UserManager服務,但找不到構造函數中使用的UserStore依賴項。 我查看了services.AddIdentityCore<User>(null) ,可以看到它沒有出現在UserStore的注冊中:

public static IdentityBuilder AddIdentityCore<TUser>(this IServiceCollection services, Action<IdentityOptions> setupAction) where TUser : class
{
  services.AddOptions().AddLogging();
  services.TryAddScoped<IUserValidator<TUser>, UserValidator<TUser>>();
  services.TryAddScoped<IPasswordValidator<TUser>, PasswordValidator<TUser>>();
  services.TryAddScoped<IPasswordHasher<TUser>, PasswordHasher<TUser>>();
  services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
  services.TryAddScoped<IdentityErrorDescriber>();
  services.TryAddScoped<IUserClaimsPrincipalFactory<TUser>, UserClaimsPrincipalFactory<TUser>>();
  services.TryAddScoped<UserManager<TUser>, UserManager<TUser>>();
  if (setupAction != null)
    services.Configure<IdentityOptions>(setupAction);
  return new IdentityBuilder(typeof (TUser), services);
}

然后,我查看了.AddIdentity<User, IdentityRole>()方法,這似乎也沒有注冊UserStore

public static IdentityBuilder AddIdentity<TUser, TRole>(this IServiceCollection services, Action<IdentityOptions> setupAction) where TUser : class where TRole : class
{
  services.AddAuthentication((Action<AuthenticationOptions>) (options =>
  {
    options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
    options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
  })).AddCookie(IdentityConstants.ApplicationScheme, (Action<CookieAuthenticationOptions>) (o =>
  {
    o.LoginPath = new PathString("/Account/Login");
    o.Events = new CookieAuthenticationEvents()
    {
      OnValidatePrincipal = new Func<CookieValidatePrincipalContext, Task>(SecurityStampValidator.ValidatePrincipalAsync)
    };
  })).AddCookie(IdentityConstants.ExternalScheme, (Action<CookieAuthenticationOptions>) (o =>
  {
    o.Cookie.Name = IdentityConstants.ExternalScheme;
    o.ExpireTimeSpan = TimeSpan.FromMinutes(5.0);
  })).AddCookie(IdentityConstants.TwoFactorRememberMeScheme, (Action<CookieAuthenticationOptions>) (o => o.Cookie.Name = IdentityConstants.TwoFactorRememberMeScheme)).AddCookie(IdentityConstants.TwoFactorUserIdScheme, (Action<CookieAuthenticationOptions>) (o =>
  {
    o.Cookie.Name = IdentityConstants.TwoFactorUserIdScheme;
    o.ExpireTimeSpan = TimeSpan.FromMinutes(5.0);
  }));
  services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  services.TryAddScoped<IUserValidator<TUser>, UserValidator<TUser>>();
  services.TryAddScoped<IPasswordValidator<TUser>, PasswordValidator<TUser>>();
  services.TryAddScoped<IPasswordHasher<TUser>, PasswordHasher<TUser>>();
  services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
  services.TryAddScoped<IRoleValidator<TRole>, RoleValidator<TRole>>();
  services.TryAddScoped<IdentityErrorDescriber>();
  services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<TUser>>();
  services.TryAddScoped<IUserClaimsPrincipalFactory<TUser>, UserClaimsPrincipalFactory<TUser, TRole>>();
  services.TryAddScoped<UserManager<TUser>, AspNetUserManager<TUser>>();
  services.TryAddScoped<SignInManager<TUser>, SignInManager<TUser>>();
  services.TryAddScoped<RoleManager<TRole>, AspNetRoleManager<TRole>>();
  if (setupAction != null)
    services.Configure<IdentityOptions>(setupAction);
  return new IdentityBuilder(typeof (TUser), typeof (TRole), services);
}

有誰知道我該如何解決UserManager 任何幫助,將不勝感激。

您在這里所做的只是測試您編寫的用於測試代碼的代碼。 而且,即使如此,您最終希望測試的代碼還是框架代碼 ,您首先不應該對其進行測試。 身份包含在廣泛的測試套件中。 您可以放心地假定類似FindByNameAsync的方法FindByNameAsync工作。 這全都是浪費時間和精力。

要進行真正的集成測試,您應該使用TestServer來執行類似Register操作的操作。 然后,您斷言“發布”到該操作的用戶實際上最終存儲在數據庫中。 將所有其他無用的代碼扔掉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM