Testing User.IsInRole in MVC.NET

I am trying to check User.IsInRole ("Administrator") in my application and actually trying to assign a user role ("Administrator") so that my test passes. I am using Scott Hanselman MvcMockHelpers to do this, and currently I have the following test.

    [Test]
    public void Create_CanInsertNewArticleView_IsNotNull()
    {
        // Arrange
        var controller = new ArticleController();

        MockRepository mockRepo = new MockRepository();
        var fakeContext = MvcMockHelpers.FakeHttpContext(mockRepo, "~/Article/Create");
        fakeContext.User.IsInRole("Administrator");

        // Act
        Article fakeArticle = FakeObjects.ReturnFakeArticle();

        var result = controller.Create(fakeArticle) as ViewResult;

        // Assert
        Assert.IsNotNull(result);
    }

However, the actual user controller is currently null.

Can someone help me and say what the correct test should be, User.IsInRole("Administrator")

Thanks for the help and time.

Johanna

+3
source share
2 answers

See this related answer for more details .


, Rhino Mocks:

var user = new GenericPrincipal(new GenericIdentity(string.Empty), null);
var httpCtx = MockRepository.GenerateStub<HttpContextBase>();
httpCtx.User = user;

var controllerCtx = new ControllerContext();
controllerCtx.HttpContext = httpCtx;

sut.ControllerContext = controllerCtx;
+1

IPrincipal , , .IsInRole("Administrator") true, fakeContext , IPrincipal .User . :

EDIT: , OP Rhino Mocks, , , Moq. Rhino, Rhino . Moq .

Rhino Mocks , :

public static HttpContextBase FakeHttpContext(this MockRepository mocks, string url, IPrincipal user)
{
        // Do the same setup as Scott does...

        // ...and add this:
        SetupResult.For(context.User).Return(user);

        mocks.Replay(context);
        return context,
}

- IPrincipal , FakeHttpContext, - .


Moq:

fakeContext = MvcMockHelpers.FakeHttpContext("~/Article/Create");
fakeUser = new Mock<IPrincipal>();
fakeUser.Expect(usr => usr.IsInRole(It.IsAny<String>())).Returns(true);
fakeContext.Expect(context => context.User).Returns(fakeUser.Object);

( : , unit test, . , , , , ...)

0

Source: https://habr.com/ru/post/1725602/


All Articles