私はMVC Music Storeサンプルアプリケーションの助けを借りてそれを管理しました。
public class DatabaseSetupTests : IDisposable
{
private MyDbContext Context { get; }
private UserManager<ApplicationUser> UserManager { get; }
public DatabaseSetupTests()
{
var services = new ServiceCollection();
services.AddEntityFramework()
.AddInMemoryDatabase()
.AddDbContext<MyDbContext>(options => options.UseInMemoryDatabase());
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<MyDbContext>();
// Taken from https://github.com/aspnet/MusicStore/blob/dev/test/MusicStore.Test/ManageControllerTest.cs (and modified)
// IHttpContextAccessor is required for SignInManager, and UserManager
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });
var serviceProvider = services.BuildServiceProvider();
Context = serviceProvider.GetRequiredService<MyDbContext>();
UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
}
....
}
その後、私は例えば、私のユニットテストでのUserManagerを使用することができます:
[Fact]
public async Task DontCreateAdminUserWhenOtherAdminsPresent()
{
await UserManager.CreateAsync(new ApplicationUser { UserName = "[email protected]" }, "IDoComplyWithTheRules2016!");
...
}
もし私のユニットテストクラスで
は、私はこのようなデータベースコンテキストとのUserManagerを設定しましたDependency InjectorがIHttpContextAccessorを解決できない場合、それに依存しているためUserManagerインスタンスを作成することはできません。 Asp.Net 5のUserManagerは、ユーザーのために(Claim、roles ...)変更すると、Cookieベースのクレームを更新するので、ユーザーのためにいくつかのHttpContextが必要になると思います(これは単なる前提です)。ログイン/ログアウトアクションとクッキーアクセス。
解決方法を見つけましたか?アカウントコントローラーのユニットテストを作成しようとしています。 – Jonathan
基本的にはxunitのサポートを待つことにしました。 – hally9k