chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
I was able to mock a security principal using RhinoMock using similar code but am not getting something in TypeMock obviously. Any suggestions would be helpful. Thanks.

[Test]
public void TestSomething()
{
    using (RecordExpectations recorder = RecorderManager.StartRecording())
    {
        Mock mockIdentity = MockManager.MockAll <IIdentity>();
        mockIdentity.ExpectAndReturn("IsAuthenticated", true);

        Mock mockPrincipal = MockManager.MockAll<IPrincipal>();
        mockPrincipal.ExpectAndReturn("Identity", mockIdentity.MockedInstance);
        mockPrincipal.ExpectAndReturn("IsInRole", true, new Type[] {typeof(string)});
    }

     //run tests
    try
    {
       _oldPrincipal = Thread.CurrentPrincipal;
       Thread.CurrentPrincipal = _newPrincipal;

       DoSomething();
    }
    finally
    {
        Thread.CurrentPrincipal = _oldPrincipal;
    }
}

[PrincipalPermission(SecurityAction.Demand, Role = "EDITOR")]
public void DoSomething()
{}
asked by kkilton (2.4k points)

3 Answers

0 votes
Hi,

You seem to have mixed two of our older APIs, Natural and Reflective mocks. Also, why not try writing this test using our new AAA API? It should be shorter and clearer - see full example below.

Let me know what you think!
Thanks,
Doron
Typemock support

public class ClassUnderTest
{
    [PrincipalPermission(SecurityAction.Demand, Role = "EDITOR")]
    public void DoSomething() {}
}

[TestClass]
public class SecurityPrincipalTests
{
    private IPrincipal backup;

    [TestInitialize]
    public void SetUp()
    {
         backup = Thread.CurrentPrincipal;
    }

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

    [TestMethod]
    [Isolated]
    public void WhenHasEditorPermissions_CanCallDoSomethingWithoutException()
    {
        IPrincipal fakePrincipal = Isolate.Fake.Instance<IPrincipal>(Members.ReturnRecursiveFakes);
        Isolate.WhenCalled(() => fakePrincipal.IsInRole("")).WillReturn(true);
        Isolate.WhenCalled(() => fakePrincipal.Identity.IsAuthenticated).WillReturn(true);
        Thread.CurrentPrincipal = fakePrincipal;

        ClassUnderTest target = new ClassUnderTest();
        target.DoSomething();
    }
}
answered by doron (17.2k points)
0 votes
Thanks for the help. Worked like a charm.

Thanks,
Kris
answered by kkilton (2.4k points)
0 votes
Cheers. Feel free to pick our brains anytime with any question; it's after all what we're here for :)

Doron
answered by doron (17.2k points)
...