Testing Security Link Demands with R#

This is more just a reference for me or anyone else that may stumble across this.


I had a set of Controller tests that I needed to set a mock object to Thread.CurrentPrincipal so I could test PrincipalPermission attributes. Off the bat I would just happily set Thread.CurrentPrincipal to my mocked user and everything worked fine.


When I ran the full suite of tests including all of my SqlCE Nhibernate tests I saw that NHibernate was throwing a TypeInitializationException from NHibernate.Cfg.Environment. After quite awhile of debugging I found that the data tests would only fail when I ran my Controller tests in conjunction with the data tests. After even more time I remembered about the Thread.CurrentPrincipal.


Normally you probably wouldn’t even notice a problem. It seemed as if though that when R# was trying to load the NHibernate Session it somehow didn’t have permission because Visual Studios Principal was changed to a mock object! An ephiany ensued followed by kicking myself in the rear.


To fix it, I just saved the CurrentPrincipal to an IPrincipal instance and set it back in the TearDown of my Controller test like so:


private IPrincipal _oldPrincipal;

[SetUp]
public void Setup()
{
    _oldPrincipal = Thread.CurrentPrincipal;
    Thread.CurrentPrincipal = _user;
}

[TearDown]
public void TearDown()
{
    Thread.CurrentPrincipal = _oldPrincipal;
}


Hopefully this post helps someone from falling into the same trap. Cheers!

Related Articles:

    Post Footer automatically generated by Add Post Footer Plugin for wordpress.

    About Sean Chambers

    I am a Senior software developer from Palm Coast, Florida. An advocate of Domain Driven Design, Behavior Driven Development, creator of FluentMigrator and community activist. I am married to my beautiful wife Erin and am the proud father of two wonderful children. I currently reside at ACI, a local insurance industry/mortgage software company that excels in creating solutions using Agile methodologies.
    This entry was posted in resharper tdd. Bookmark the permalink. Follow any comments here with the RSS feed for this post.