Test Authorizatoin Rules in CSLA

To test CSLA BO’s authorization settings, I have to mock the IPrincipal.IsInRole method, RhinoMock example like this:

        public void CanHideForUnAuthorizedUser()
            MockRepository mocks = new MockRepository();
            IPrincipal mockPrincipal = (IPrincipal)mocks.CreateMock<IPrincipal>();
            Csla.ApplicationContext.User = mockPrincipal;

            using (mocks.Record())


            }// Replay and validate interaction
            Order obj = null;
            using (mocks.Playback())
                obj = Order.GetOrder(new Guid("c512e473-19fd-401c-80f6-055cf239e461"));

            }// Post-interaction assertions


        public void CanGetOrderUsingTypeMock()

            // Setup Stud Data to be returned from mocked repository.
            // This code could be moved into record expectation block
            // but we assume everything inside that block is mocked.
            // to reduce confusion, just leave it here.
            // In fact , this mode is faster comparing the other one.
            OrderDTO stubOrderDTO = new OrderDTO();
            stubOrderDTO._OrderNumber = "12345";

            // Everything inside recorder block will be mocked.
            // expect the settng return value line: recorder.Return()
            using (RecordExpectations recorder = RecorderManager.StartRecording())
                // Don't have to mock the IPricipal object "User"
                // Here TypeMock is too powerful. no need to think.

                OrderRepository mockRepository = new OrderRepository();

            Order p = Order.GetOrder(Guid.Empty);
            Assert.AreEqual("12345", p.OrderNumber);

After using typemock for a while, I suddenly tired of Rhino’s record-play syntax, looking into MoQ’s doc, it’s very similar to TypeMock, but it’s LinQ syntax (var and Lamba) are only available on 3.5 framework.

If using MoQ, the Rhino example will shorten to:

        public void CanHideForUnAuthorizedUser()
            var mock = new Mock<IPrincipal>();
            mock.Expect(x => x.IsInRole("user")).Returns(true);
            Csla.ApplicationContext.User = mock;

            var obj = Order.GetOrder(new Guid("c512e473-19fd-401c-80f6-055cf239e461"));


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s