tags:

views:

20

answers:

1

The following test works fine with .Net 3.5 + NUnit 2.4.8. But the same tests does not work using .Net 4.0 + Nunit 2.5.7.10213.

/// <summary>
/// This test fails with unexpected exception:
///    System.InvalidCastException : Unable to cast object of type 
///    'System.Security.Principal.GenericPrincipal' to type 
///    'System.Security.Principal.WindowsPrincipal'.
/// </summary>
[Test]
public void GiventATest_WhenSettingDomainPrincipal_AccessingThreadcurrentPrincipalWorks()
{
    AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
    WindowsPrincipal currentUserWindowsPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
}

The wierd thing is that after the test has failed once, I can run the tests again and it works until I reload the test assembly. And then, it fails again on the first attempt.

A: 

Hi, add this before your test:

NUnit.Core.TestContext.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

You will need to add a reference to NUnit.Core.dll if you do not have it already. Be aware that there are two classes TestContext, one in NUnit.Framework namespace and one in NUnit.Core namespace

Termit