2016-12-16 10 views
1

の外には、ここに私のコードです:ここではのHttpContext部品番号私はテストケース</p> <p>の.NETコア1.0.0でのHttpContextをMOQしたいAsp.Netコアのコントローラ

public async Task<string> Login(string email, string password) 
{ 
var result = await _signInManager.PasswordSignInAsync(email, password, false, lockoutOnFailure: false); 
if (result.Succeeded) 
    { 
     return HttpContext.User.Identity.Name; 
    } 
    else 
    { 
     return ""; 
    } 
} 

は私のテストケース

です
[Fact] 
public async Task Login() 
{ 
    ApplicationUser user = new ApplicationUser() { UserName = "[email protected]", Email = "[email protected]", Name = "siddhartha" }; 
    await _userManager.CreateAsync(user, "[email protected]"); 
    var userAdded = await _userManager.CreateAsync(user); 
    var result = await Login("[email protected]", "[email protected]"); 
    Assert.Equal("siddhartha", result); 
} 

それはエラーメッセージを取得し、失敗行く:

HttpConテキストはnullであってはなりません。ここで

私のサービスである - startup.cs

public void ConfigureServices(IServiceCollection services) 
    { 
     services.AddIdentity<ApplicationUser, IdentityRole>() 
      .AddEntityFrameworkStores<PromactOauthDbContext>() 
      .AddDefaultTokenProviders(); 
     services.AddMvc().AddMvcOptions(x => x.Filters.Add(new GlobalExceptionFilter(_loggerFactory))); 
    } 
+0

私がこれに気付かなかったのでしょう。この

public void ConfigureServices(IServiceCollection services) { var authenticationManagerMock = new Mock<AuthenticationManager>(); var httpContextMock = new Mock<HttpContext>(); httpContextAccessorMock.Setup(x => x.HttpContext.User.Identity.Name).Returns("Siddhartha"); httpContextMock.Setup(x => x.Authentication).Returns(authenticationManagerMock.Object); var httpContextAccessorMock = new Mock<IHttpContextAccessor>(); httpContextAccessorMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object); var httpContextMockObject = httpContextAccessorMock.Object; services.AddScoped(x => httpContextAccessorMock); services.AddScoped(x => httpContextMockObject); serviceProvider = services.BuildServiceProvider(); } 

のようなテストケースプロジェクトに

登録のHttpContextリポジトリ内のHttpContextを使用まず、あなたのファクトテストメソッドと同じクラスの実際のログインメソッドですか?コントローラを作成せずにログインを直接呼び出すテストはどのように行われますか?コントローラを作成していない場合は、モックを渡すことはできません。 –

答えて

0

私はエラーがSignInManagerのコンストラクタにnullのチェックからであると考えています。あなたのテストのためにSignInManagerをどのように構築したのかわからないので、何かを渡したかどうかわからないけど、そうは思わない。

この場合、IHttpContextAccessorのモックを作成し、新しいDefaultHttpContext()を返すようにHttpContextプロパティを設定し、その模擬オブジェクトをSignInManagerに渡します。

+0

あなたの提案通り、私は試しましたが、まだ動作していません。 @Runesun –

+0

もっとコードを提供する必要があります。私はどのようにあなたのマネージャの依存関係(すなわちSignInManager)を提供されたコードで構築するのか分からない。 –

2

コントローラを使用しないでください。私は.netコアにmoq HttpContextを持っています。その後、あなたはHttpContext.User.Identity.Name =シッダールタ

public async Task<string> Login(string email, string password) 
{ 
var result = await _signInManager.PasswordSignInAsync(email, password, false, lockoutOnFailure: false); 
    if (result.Succeeded) 
    { 
     return HttpContext.User.Identity.Name; 
    } 
    else 
    { 
     return ""; 
    } 
} 
関連する問題