Category Archives: test

Using Exception in Wcf should be very caucious, as I blogged before, wcf exception should be marked as Serializable, and implement all 4 ctor from base exception class. An unit-test for each exception might be overkill, but it’s worth to try.

In-proc wcf host is neat for this purpose, by using channel Factory, client side doesn’t need configuration either.

    [TestFixture]
    public class MyDataNotFoundExceptionSpecs
    {
        private readonly ServiceHost _host;
        private const string _url = "net.tcp://localhost:9000/TestException";

        public MyDataNotFoundExceptionSpecs()
        {
            _host = new ServiceHost(typeof(TestService));

            _host.AddServiceEndpoint(typeof(ITestService),
                new NetTcpBinding(), _url);
            _host.Open();
            Console.WriteLine("wcf service started.");
        }

        ~MyDataNotFoundExceptionSpecs()
        {
            _host.Close();
        }
            private ChannelFactory<ITestService> channelFactory;
            [SetUp]
            public void SetupChannelFacotry()
            {
                channelFactory = new ChannelFactory<ITestService>(
                   new NetTcpBinding(),
                   new EndpointAddress(_url));
            }
            [TearDown]
            public void CleanUpChannelFacotry()
            {
                    channelFactory.Abort();
            }
        [Test]
        [ExpectedException(typeof(FaultException<MyDataNotFoundException>))]
        public void should_passed_to_client()
        {
            ITestService proxy = channelFactory.CreateChannel();

            proxy.Ping("Frank");

          }

    }

    public class TestService : ITestService
    {
        public void Ping(string user)
        {
            throw new FaultException<MyDataNotFoundException>(new MyDataNotFoundException());
        }
    }

    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        [FaultContract(typeof(MyDataNotFoundException))]
        void Ping(string user);
    }

When first starting NH mapping, we just want to make sure the data is really being deleted, for cascaded child, some tricky code are needed to work around the strong relationship we created in domain entities. SqlQuery is one of those.


[Test]
 public void Should_delete_email()
 {
 // Retrieve
 Organization org = _repository.FetchById(8172);

 // Ensure org was retrieved.
 Assert.That(org, Is.Not.Null);

 var emailToAdd = new Email("Home Alternate", "x@y");
 org.AddEmail(emailToAdd);

 _repository.Update(org, org.LastModifiedDate);
Assert.That(emailToAdd.Id == 0);
_session.Flush();
Assert.That(emailToAdd.Id > 0);

 // Delete
 org.DeleteEmail(emailToAdd);
 _session.Flush();

 // Ensure email data is physically deleted
 ISQLQuery query = _session.CreateSQLQuery("select * from Stakeholder_Email_CV where stakeholder_email_id = " +
 emailToAdd.Id);
 Assert.That(query.List().Count == 0);

 }

Quite interesting testing code for NHibernate mapping.

Very interesting topic, Jeremy’s IMessageBoxService idea is very easy to handle, unit-test. The pain is have to inject this IMessageBox to every class needed.

Glenn Block’s suggestion is using event handler, code can be a little bit cleanner. Test is a little bit harder.


[Test]
 public void should_validate_new_mail_role_and_raise_show_message_event()
 {
    var subscriber = MockRepository.GenerateMock<IEventSubscriber>();
     _emailRoleMaintViewModel.ShowMessageEvent
     += new System.EventHandler<EventArgs<string>>(subscriber.Handler);

     subscriber.Expect(x=>x.Handler( _emailRoleMaintViewModel, new EventArgs<string>("") ))
     .IgnoreArguments();

     _emailRoleMaintViewModel.AddEmailRole("");

     subscriber.VerifyAllExpectations();

 }

More difficult problem is to get the confirmation from view, Glenn’s solution is ‘to raise a separate event to indicate selection which the VM subscribes to‘. Too much overkill for a simple messagebox.

Dong Scott’ s post about CancellableCommand is another option, ViewModel only focus on success logic, but give options to view to ‘cancel’ the action. The comfirmation rending and analyzing code won’t be testable then, but who cares? It’s just a messagebox.


public class CancellableCommand : RelayCommand
{

   public void Execute(object parameter)
   {
   var eventHandler = Executing;
   CancelEventArgs cancelEventArgs = new CancelEventArgs(true);
   if (eventHandler != null)
   {
     eventHandler(parameter, cancelEventArgs);
   }

   if (cancelEventArgs.Cancel) return;

    _execute(parameter);
   }

    public event CancelEventHandler Executing;

}

[Test]
 public void should_stop_if_view_cancel()
 {
 var subscriber = MockRepository.GenerateMock<IEventSubscriber<CancelEventArgs>>();
 _emailRoleMaintViewModel.DeleteCommandObject.Executing +=
 new CancelEventHandler(subscriber.Handler);

 subscriber.Expect(x => x.Handler(_emailRoleMaintViewModel, new CancelEventArgs(true)))
 .IgnoreArguments();

 _emailRoleMaintViewModel.DeleteCommandObject.Execute("");

 subscriber.VerifyAllExpectations();
 _mockLookupProxy.AssertWasNotCalled(x => x.DeleteEmailRole(null), opt => opt.IgnoreArguments());

 }

 [Test]
 public void should_delete_if_view_did_not_cancel()
 {
 var subscriber = MockRepository.GenerateMock<IEventSubscriber<CancelEventArgs>>();
 _emailRoleMaintViewModel.DeleteCommandObject.Executing +=
 new CancelEventHandler(subscriber.Handler);

 subscriber.Expect(x => x.Handler(_emailRoleMaintViewModel, new CancelEventArgs(true)))
 .IgnoreArguments()
 .Do(new EventHandler<CancelEventArgs>(
 (o, e) => { e.Cancel = false; }
 ));

 _emailRoleMaintViewModel.DeleteCommandObject.Execute("");

 subscriber.VerifyAllExpectations();
 _mockLookupProxy.AssertWasCalled(x => x.DeleteEmailRole(null), opt => opt.IgnoreArguments());
 }

    public interface IEventSubscriber<TEventArgs> where TEventArgs : EventArgs
    {
        void Handler(object sender, TEventArgs e);
    }

I should have added this option in my test earlier, then I won’t waste 2+ hours today. The reason causing problem was very simple, AssertWasCalled() method in current verion RhinoMocks (3.5.0.1337 RC) doesn’t action consistently. I think it’s because comparing the object reference equalty. I had to add options=>options.IgnoreArguments() to get around from this.

Here is a piece of my MVP + CLSA test. Struggled for a while with Property setter, thanks God, it isn’t that hard.


    [TestFixture]
    public class When_initializing_view : EstablishContext
    {
        [Test]
        public void should_call_view_setter_if_id_exists()
        {
            // Arrange
            _mockOrganizationRepository.Expect(x => x.FindById(1)).Return(_stubOrganizationDTO);

            _mockView = MockRepository.GenerateMock<IEditDetailsView<OrganizationBO>>();

            _presenter = new EditDetailsPresenter<OrganizationBO>(_mockView);

            // Action
            _presenter.InitViewFor(1);

            // Assert
            _mockView.AssertWasCalled(x => x.CurrentBO = null,
                options =>options.IgnoreArguments() );
        }
    }

I then created a generic EditDetailsPresenter, worked as I expected with one concern left: How to mock DataPortal directly. Currently I am still mocking repository. Ideally I should mock DataPortal instead, otherwise I have to make sure there is at least one BO is fully functional.

Mocking DataPortal is very hard, because those Fecth, Create, Update and Delete are all static methods, I had to create an adapter to wrap those static methods, then using StructreMap again inside adapter enable switching between DataPortal and mock DomainDAO, here is what I have tried:

  1. Create DomainDAO and IDomainDAO,
    public class DomainDAO<BO> : IDomainDAO<BO>
    {
    public BO Fetch(object criteria)
    {
    return DataPortal.Fetch<BO>(criteria);
    }
    
    public BO Create()
    {
    return DataPortal.Create<BO>();
    }
    
    public BO Update(BO bo)
    {
    return DataPortal.Update<BO>(bo);
    }
    
    public void Delete(object criteria)
    {
    DataPortal.Delete<BO>(criteria);
    }
    }
    
    public interface IDomainDAO<T>
    {
    T Fetch(object criteria);
    T Create();
    T Update(T bo);
    void Delete(object criteria);
    }
    
  2. Create DAOManager to Get DomainDAO:
    public static class DAOManager
    {
    public static IDomainDAO<BO> DomainDAO<BO>()
    {
    return ObjectFactory.GetInstance<IDomainDAO<BO>>();
    }
    }
    
  3. Change classic factory method in BO from DataPortal to this new DAOManager.
    public static OrganizationBO GetOrganizationBO(int stakeholderId)
    {
    return DAOManager.DomainDAO<OrganizationBO>().Fetch(new SingleCriteria<OrganizationBO, int>(stakeholderId));
    //            return DataPortal.Fetch<OrganizationBO>(new SingleCriteria<OrganizationBO, int>(stakeholderId));
    }
    
  4. The presenter testing code can be changed to:
    
    [SetUp]
    public void SetUp()
    {
    _mockService = MockRepository.GenerateMock<IDomainDAO<OrganizationBO>>();
    ObjectFactory.Inject<IDomainDAO<OrganizationBO>>(_mockService);
    }
    
    [TearDown]
    public void TearDown()
    {
    ObjectFactory.ResetDefaults();
    }
    
    [TestFixture]
    public class When_initializing_view : EstablishContext
    {
            [Test]
            public void should_call_view_setter_if_id_exists()
            {
                // Arrange
                // We don't need to set return value here.
                _mockService.Expect(x => x.Fetch(new SingleCriteria<OrganizationBO, int>(68190)));
    
                _mockView = MockRepository.GenerateMock<IEditDetailsView<OrganizationBO>>();
    
                _presenter = new EditDetailsPresenter<OrganizationBO>(_mockView);
    
                // Action
                _presenter.InitViewFor(68190);
    
                // Assert
                _mockView.AssertWasCalled(x => x.CurrentBO = null,
                    options => options.IgnoreArguments() );
            }
    
            [Test]
            public void should_set_error_msg_in_view_if_id_not_exists()
            {
                // Arrange
                Exception ex = new Exception("Data Not Found", new DataNotFoundException());
                _mockService.Expect(x => x.Fetch(new SingleCriteria<OrganizationBO, int>(1)))
                    .IgnoreArguments()
                    .Throw(new DataPortalException("DataPortal.Fetch failed.",
                        ex,
                        null)); // See, we don't have to mock BO here, unless you try to read BO through exception in UI.
    
                _mockView = MockRepository.GenerateMock<IEditDetailsView<OrganizationBO>>();
    
                _presenter = new EditDetailsPresenter<OrganizationBO>(_mockView);
    
                // Action
                _presenter.InitViewFor(1);
    
                // Assert
                _mockView.AssertWasCalled(x => x.ShowError(null),
                    options => options.IgnoreArguments() );
            }
    

Fetch can be done this way, but I can’t mock Save() because it’s deep in Csla, unless I can override BusinessBase.Save() which is another mission impossible (too many internal classes involved). To make Csla TDD friendly, let ask for TypeMock to save us out.

 [TestFixture]
    public class When_view_firing_save_event : EstablishContext
    {
        [Test]
        public void should_set_success_msg_and_set_new_BO_in_view_if_save_new_bo_succeed()
        {
            // Arrange
            OrganizationBO orgBo = DataPortal.Create<OrganizationBO>();
            orgBo.Name = "test Org";
            Assert.That(orgBo.IsValid, orgBo.GetValidationMessage());

            _mockView = MockRepository.GenerateMock<IEditDetailsView<OrganizationBO>>();
            _mockView.Stub(x => x.CurrentBO).Return(orgBo).Repeat.Any();

            _presenter = new EditDetailsPresenter<OrganizationBO>(_mockView);

            // This won't work, because BusinessBase.Save() is tightly coupled to DataPortal.
            //_mockService.Expect(x => x.Update(orgBo)).IgnoreArguments();

            // Use TypeMock to mock DataPortal.Update() inside BusinessBase.Save()
            using (RecordExpectations recorder = RecorderManager.StartRecording())
            {
                  // CAUTION: ALL calls here are mocked!!!
                  recorder.DefaultBehavior.IgnoreArguments();
                  recorder.ExpectAndReturn(DataPortal.Update(orgBo), orgBo);
            }

            // Action
            _mockView.Raise(x => x.RequestSave += null, this, EventArgs.Empty);

            // Assert
            _mockView.AssertWasCalled(x => x.CurrentBO = null,
                                      options => options.IgnoreArguments());

            _mockView.AssertWasCalled(x => x.ShowMessage(null),
                                      options => options.IgnoreArguments());

    }

We can remove DomainDAO then if using TypeMock to mock DataPortal.

The new ObjectFactory in CSLA 3.6 seems can make this mock easier, looks like your own ObjectFactory is not static class anymore, different than DataPortal. By creating your own IDataPortal or IObjectFactory, as Ryan did,  mocking those service layer objects should become possible. Someday I will look into this CSLA.ObjectFactory thing if we aren’t going to TypeMock. Rocky’s statement indicates this will be a lot of work:

It is very important to realize that when using this factory model, the data portal does virtually nothing for you. It doesn’t automatically call MarkOld(), MarkNew() or MarkAsChild(). You assume total responsibility for creating and initializing the business object graph, and for setting the state of all objects in the graph.

But it seems Ryan’s ObjectFactroy sample code already finished most of them. One thing doesn’t fit our situation is, we need IRepository<> changed to IDomainObjectRepository in Factory.


        private readonly IRepository<T> _repository;
        public BusinessBaseServerFactory(IRepository<T> repository)
        {
            _repository = repository;
        }

So far, I think unless CSLA.ObjectFactory can provide an optional attribute something like “RepositoryType”, I have to create One ObjectFacotry per BO. Our libaray will become more messier.

Do we need to separate concern between parent object and its child? Say we have a stakeholder BO, which can have multiple email BOs, (an email BO collection). Then where should we place those specs/unit-tests for email BO?

Because emailBO is a child BO, the normal way to save it should be only through stakeholderBO.Save(). It’s possible that stakeholderBO might still be work-in-progress, or having problem caused by other childBO, e.g., telephoneBO. Or more likely, it’s not finish yet. Can we still work on EmailBO without worry too much about it’s parent – StakeholderBO?

So seperate concern is necessary. We need an interface to implement design-by-contract.

Create an IStakeholder interface, mock it in emailBO unit-test. (Thanks to Rhino, we don’t need worry about data portal any more. ) But we need to explicitly call SetParent() in emailBOCollection to simulate the LoadProperty behavior in stakeholderBO.

The test code:


            // Arrange
            var emailRepository = MockRepository.GenerateMock<IEmailRepository>();
            ObjectFactory.Inject<IEmailRepository>(emailRepository);

            EmailDTO OneValidTestDTO = new EmailDTO()
                                           {
                                               Address = "2@d.c", EmailRole = "Home",
                                               StakeholderId = 123, StakeholderEmailId = 456
                                           };

            emailRepository.Expect(x => x.Insert(null)).IgnoreArguments().Return(OneValidTestDTO);
            // or play the new inline constraints syntax
            emailRepository.Expect(x => x.Insert(Arg<EmailDTO>.Is.Anything)).Return(OneValidTestDTO); 

            IStakeholder mockStakeholderBO = MockRepository.GenerateMock<IStakeholder>();  

            // Action
            EmailBOCollection emails = EmailBOCollection.NewEmailBOCollection();

            // SetStakeholder is created in EmailBOCollection to call private SetParent through reflection.
            // This is optional because the second parm in DataPortal.UpdateChild() will be passed
            // to child_XYZ() as the parameter which is the real parent.
            // emails.SetStakeholder(mockStakeholderBO);   // IStakeholder should extend csla.IParent.

            var newEmail = emails.AddNew();
            // Make this new EmailBO valid.
            newEmail.Address = "1@dc.com";
            newEmail.EmailRole = "Home";

            Assert.That(emails[0].BrokenRulesCollection, Is.Empty, emails[0].BrokenRulesCollection.ToString());

            // this is to simulate the parent.Save() in the real world,
            DataPortal.UpdateChild(emails, mockStakeholderBO);
            // We don't want and can't call stakeholder.Save() here

            // Assert
            Assert.That(emails[0].StakeholderEmailId == OneValidTestDTO.StakeholderEmailId);
            Assert.That(emails[0].StakeholderId == OneValidTestDTO.StakeholderId);  

            // Reset to default
            ObjectFactory.ResetDefaults();

Unfortunately, SetParent(IParent) is a private method in IEditableObject and IEditableCollection. I had to create a public wrapper in my base class.


        public void SetStakeholder(IParent parent)
        {
            object[] parm = new object[] { parent };

            var method = this.GetType().GetMethod("Csla.Core.IEditableCollection.SetParent", BindingFlags.Instance | BindingFlags.NonPublic);

            method.Invoke(this, parm);
        }

But, later I figured out it’s not necessary, only if I am doing some parent-related validation in emailBO, say, an Organization type stakeholder can not have home email role.

Dataportal.Update() method is key to simulate parent.Save(), this old (3.0) syntax works great in my mock/TDD solution to CSLA.

I wish I had used Aptana studio (Radrails) 2 years ago, so my ruby coding experience could be more fun. This IDE is very close to Visual studio + Resharper for CSharp coding. The intelligence looks a little bit werid, might because there are too many method in ruby’s object type.

What else I like very much includes:

  1. Unite-test view, exactly same as Junit in eclipse. Once I run one of the test case, it seems no way back to the full list. Unless I re-run the class level test or select the latest test I had run.
  2. Outline view, can even launch unit-test directly. But for the method level unit-test I had to hard type in class name and method name, why no smart drop down list available?
  3. Ruby core api help window, not that help than MS one, but better than nothing.
  4. Code compete, for method, if block, etc. Same as Resharper does for CSharp.
  5. Open declaration, very useful, F3, just like Ctrl+B in R#. But it seems not very stable, I kept getting error “select text not in a ruby …”, switch to eclipse, work for a while, then got the same problem again. For some reason, my home pc just work fine. Need to figure this out someday.
  6. Looks like this aptana studio can also do php and python coding, even ajax javascript, WOW!

The annoying part for Ruby coding is environment config. For some reason my libxml didn’t work on my windows env, figured out almost whole day, then it magiclly starts to word. Still don’t know why. Probably I should copy those lib2xml.dll into windows system folder, and then copy the xml folder under $ruby\lib\ruby\site_ruby\1.8. But I was too tired of copying those folders, don’t know what one did the work. Anyway, it works now, PFM.

Those files are needed for libxml running on windows.

  1. ruby\lib\ruby\site_ruby\1.8\xml\libxml.rb
  2. ruby\lib\ruby\site_ruby\1.8\i386-msvcrt\libxml_so.so
  3. ruby\lib\ruby\site_ruby\1.8\libxml.rb

I also got a problem on installing log4r, tried gem install, update_rubygems, didn’t work, always got a loaderror. I tried “ruby -e ‘require “log4r”‘, the log4r already shonw in the list, but why still loaderror?

I ended up with download the tgz file, and run the ruby install.rb, it seems this process is doing lots of file links afterwards. So, it works. A new folder log4r was created under “ruby\lib\ruby\site_ruby\1.8\”, different than gem install.

Look into log4r, 5 methods in it, debug, info, warn, error and fatal, extact same as log4net. I remeber somewhere in my app I use a trace, it seems not a standard one.

We use Repository Pattern inside our CSLA BO to extract data access code into a separate class – repository object,  because we use interface IRepository to loose couple BO and concrete Repository object and implement “design by contract”, so BO doesn’t care which technology repository is using, either using ADO.net or Linq to SQL, or NHinbernate or Entity Framework .

The benefits of using this model include:

  • Loose coupling between BL and DAL
  • Easy to switch to different Data Access technology
  • Central place to control and switch IOC container

Updated at Feb. 09, 2009:
Found this post about the difference between DAO and Repository pattern. Yes, my model is more similar to DAO, because I was following one Repo/DAO per table rule. In fact, I’m on the progress of switching to the new Csla.ObjectFactory which is a real repository class, or, at lease, can be a repository wrapper, as Ryan did in his example.

I couldn’t make Roy’s XtUnit working in my test cases. Tried to switch to MbUnit, but Resharper 4 still doesn’t support it yet. Later, I found there are some posts (here, and here) pointing out the very easy solution for this: System.Transactions.TransactionScope.

I then adopt this trick, created my own DBTestFixtureInTheRollBackTransactionclass.

It works, and like the author said, embarrassingly simple!

I have a html page to display xml files from the same server. The reasons I didn’t use the server side script includes

  1. ruby needs rails, but I don’t want to create an application for this single page. I tried to run ruby as cgi, no success.
  2. maggiePie can make php eaiser, but I think it’s still kind of overkill for this simple use.

Then I turned to client-side javascript. At first I use this function to load xml file:

function loadXMLtoDIV(file, div_name) {

var xmlDoc = null;

var moz = (typeof document.implementation != ‘undefined’)
&& (typeof document.implementation.createDocument != ‘undefined’);
var ie = (typeof window.ActiveXObject != ‘undefined’);

if (moz) {

xmlDoc = document.implementation.createDocument(“”, “”, null);
xmlDoc.load(file);
xmlDoc.onload = function() { readXML(xmlDoc, div_name); };

} else if (ie) {

xmlDoc = new ActiveXObject(“Microsoft.XMLDOM”);
xmlDoc.async = false;
while(xmlDoc.readyState != 4) {};
xmlDoc.load(file);
readXML(xmlDoc, div_name);
}

}

It worked very well, and I like it until I tried use jQuery:

function XmlOnLoad( xmlData, divId ){

// Get the first 2 items
var jItems = jQuery(‘item:lt(2)’, xmlData);

var jDiv = $( divId );

// reset.
jDiv.html(”);

jItems.each(
function( ){
jDiv.append( $(this).find(‘pubDate’).text() + ‘ : ‘ +$(this).find(‘title’).eq(0).text() +’<br/>’);
}
);
}
function GetXMLData(file, divId){
$.get(file,{},
function(xmlData, status) {
XmlOnLoad(xmlData, divId);
} );

}

And another benefit from jQuery is, I can move those ‘behavior’ from the presentation part. This jQuery ‘onload’ function is to add an universal click event to all the itemlist class div. By doing this my html elements look much neater.

$(function(){

$(“div.itemlist”).each(

function(n){
var current = this;

$(“<a href=”>See latest items … </a>”).click(  function(event){
GetXMLData(   “#”+current.id); return false;}  ).appendTo($(this));
}
);

})

One thing I still don’t understand, if I tried to load too many xml file into the page elements, some xml files just missed. jQuery still doesn’t fix this problem. But coverting from loading to ajax using jQuery is so easy, so I didn’t spent too much time on it at all.

For those TDD fans, you want to look in this QUnit intro.

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

        [Test]
        [ExpectedException("System.Security.SecurityException")]
        public void CanHideForUnAuthorizedUser()
        {
            MockRepository mocks = new MockRepository();
            IPrincipal mockPrincipal = (IPrincipal)mocks.CreateMock<IPrincipal>();
            Csla.ApplicationContext.User = mockPrincipal;

            using (mocks.Record())
            {

                Expect.Call(mockPrincipal.IsInRole("user")).Return(false);

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

            }// Post-interaction assertions
            Assert.IsNull(obj);

        }

         [Test]
        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.
                Csla.ApplicationContext.User.IsInRole("user");
                recorder.Return(true);

                OrderRepository mockRepository = new OrderRepository();
                mockRepository.GetById(Guid.Empty);
                recorder.Return(stubOrderDTO);
            }

            Order p = Order.GetOrder(Guid.Empty);
            Assert.IsNotNull(p);
            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:


       [Test]
        [ExpectedException("System.Security.SecurityException")]
        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"));
        }