2016-12-03 7 views
1

、このアクションフィルタは、ユーザーのアクティビティをログに記録すると仮定されていますASP.NETコアでカスタムアクションフィルターをテストする方法は?私は私のASP.NET Coreアプリケーションに簡単なアクションフィルタを作成した

public class AuditAttribute : IResultFilter 
{ 
    private readonly IAuditService _audit; 
    private readonly IUnitOfWork _uow; 
    public AuditAttribute(IAuditService audit, IUnitOfWork uow) 
    { 
     _audit = audit; 
     _uow = uow; 
    } 
    public void OnResultExecuting(ResultExecutingContext context) 
    { 
     ar model = new Audit 
     { 
      UserName = context.HttpContext.User, 
      //... 
     }; 
     _audit.Add(model); 
     _uow.SaveChanges(); 
    } 
    public void OnResultExecuted(ResultExecutedContext context) 
    { 
    } 
} 

は今、私はちょうど私がそれのためのユニットテストを書くことができる方法を知りたいと思いました。私は使用していますxUnitMock

+0

モック必要なすべての依存関係をテスト対象のメソッドを行使して、Nkosiが、私はAAAに従うだろう、と述べたのと同じ方向で実際の動作 – Nkosi

+1

に対して期待される動作を確認してください:とにかく、これはあなたの試験方法は次のようになります方法ですパターン。アサインアサートアサート コントローラをテストする方法はこちら https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/testing – DOMZE

答えて

0

あなたのコードによれば、ユニットテストを行うには、HttpContextもモックする必要があります。 このビットは正しく表示されません:UserName = context.HttpContext.UserUserName = context.HttpContext.User.Identity.Nameを意味すると思います。 、

public void OnResultExecuting_Test() 
{ 
    // Arrange sesction : 
    var httpContextWrapper = new Moq<HttpContextBase>(); 
    var genericIdentity = new GenericIdentity("FakeUser","AuthType"); 
    var genericPrincipal = new GenericPrincipal(genericIdentity , new string[]{"FakeRole"}); 
    httpContextWrapper.Setup(o=> o.User).Return(genericPrincipal); 
    var controller = new FakeController(); // you can define a fake controller class in your test class (should inherit from MVC Controller class) 
    controller.controllerContext = new ControllerContext(httpContextWrapper.Object, new RouteData(), controller); 
    var audit = new Moq<IUnitOfWork>(); 
    var uow = new Moq<IAuditService>(); 
    // more code here to do assertion on audit 
    uow.Setup(o=>o.SaveChanges()).Verifiable(); 
    var attribute= new AuditAttribute(audit.Object,uow.Object); 

    // Act Section: 
    attribute.OnActionExecuting(filterContext); 

    // Assert Section: 
    ... // some assertions 
    uow.Verify(); 

} 
+1

「filterContext」はどこから来たのですか? – lbrahim

関連する問題