如何模拟owin的authorizationManager来测试我的api控制器

时间:2015-01-28 15:49:10

标签: c# unit-testing mocking owin thinktecture-ident-model

我在WebApi中使用ThinkTecture's resource based authorization

我试图测试我的一个控制器,我需要检查该功能内部的访问权限。但是现在,我不能再测试这个函数了,因为我不能模拟扩展方法,因为它是一个nuget方法,我不能修改类来注入另一个值。 / p>

我的控制器看起来像这样:

public class AlbumController : ApiController
{
    public async Task<IHttpActionResult> Get(int id)
    {
        if (!(await Request.CheckAccessAsync(ChinookResources.AlbumActions.View, 
                                            ChinookResources.Album,
                                            id.ToString())))
        {
            return this.AccessDenied();
        }

        return Ok();
    }
}    

并将ResourceAuthorizationManager设置为启动,如下所示:

app.UseResourceAuthorization(new ChinookAuthorization());    

ThinkTecture项目的源代码是here

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

你总是可以将这个静态调用包装成你的一些抽象:

public interface IAuthorizationService
{
    Task<bool> CheckAccessAsync(string view, string album, string id);
}

然后有一些实现将委托调用静态扩展方法。但是现在你将使用IAuthorizationService,你可以在单元测试中自由地模拟CheckAccessAsync方法。

就测试这个抽象的实现而言,你可能不需要它,因为它只是作为ThinkTecture类的桥梁,它应该已经经过了很好的测试。

答案 1 :(得分:1)

我终于解决了我的问题。 真正的问题是CheckAccess方法是一个扩展。 (对于我的回答,每个班级都会引用可以找到的样本here

要停止使用扩展方法,我将这些方法添加到我的chinookAuthorization

   public Task<bool> CheckAccessAsync(ClaimsPrincipal user, string action, params string[] resources)
    {
        var ctx = new ResourceAuthorizationContext(user ?? Principal.Anonymous, action, resources);

        return CheckAccessAsync(ctx);
    }

    public Task<bool> CheckAccessAsync(ClaimsPrincipal user, IEnumerable<Claim> actions, IEnumerable<Claim> resources)
    {
        var authorizationContext = new ResourceAuthorizationContext(
            user ?? Principal.Anonymous,
            actions,
            resources);

        return CheckAccessAsync(authorizationContext);
    }    

然后我改变了我的控制器以获得chinookAuthorization的实例

public class AlbumController : ApiController
{
    protected readonly chinookAuthorization chinookAuth;

    public BaseApiController(chinookAuthorization chinookAuth)
    {
        if (chinookAuth == null)
            throw new ArgumentNullException("chinookAuth");

        this.chinookAuth = chinookAuth;
    }
    public async Task<IHttpActionResult> Get(int id)
    {
        if (!(await chinookAuth.CheckAccessAsync((ClaimsPrincipal)RequestContext.Principal, ChinookResources.AlbumActions.View, 
                                        ChinookResources.Album,
                                        id.ToString())))
        {
            return this.AccessDenied();
        }

        return Ok();
    }
}

我仍然将我的ChinookAuthorization声明为我的owin启动,继续使用相同的模式进行属性检查访问调用。

所以现在,我只需要嘲笑chinookAuthorization,模拟调用返回true的响应,就是这样!

答案 2 :(得分:1)

ResourceAuthorizationAttribute使用Reqest.CheckAccess,所以我不认为抽象实现然后将其注入控制器是一个很好的解决方案,因为理论上,ResourceAuthorizationAttribute和创建的服务可以使用不同的实现CheckAccess方法。

我通过创建BaseController

采用了一种更简单的方法
public class BaseController : ApiController
{
        public virtual Task<bool> CheckAccessAsync(string action, params string[] resources)
        {
            return Request.CheckAccessAsync(action, resources);
        }
}

并使CheckAccessAsync成为虚拟所以我可以模拟它(例如Moq)。

然后从我的控制器

public class AlbumController : BaseController
{
    public async Task<IHttpActionResult> Get(int id)
    {
        if (!(await CheckAccessAsync(ChinookResources.AlbumActions.View, 
                                            ChinookResources.Album,
                                            id.ToString())))
        {
            return this.AccessDenied();
        }

        return Ok();
    }
}

然后对控制器进行单元测试就像以下一样简单:

[TestClass]
public class TestClass
{
    Mock<AlbumController> mockedTarget
    AlbumController target

    [TestInitialize]
    public void Init()
    {
        mockedTarget = new Mock<AlbumController>();
        target = mockedTarget.Object;
    }

    [Test]
    public void Test()
    {
        mockedTarget.Setup(x => x.CheckAccessAsync(It.IsAny<string>(),
            It.IsAny<string[]>()))
            .Returns(Task.FromResult(true));

        var result = target.Get(1);

        // Assert
    }

}