The following code throws an UnauthorizedAccessDenied exception (0x80070005) when run as a unit test in MSTest, however it works when run on a web page. The username is my domain user:

public class MyTests

    public void Blah_ValuesGiven_SiteCreated()
        SPUserToken sysUserToken = null;
        using (SPSite spfarmSite = new SPSite("http://myserver.com"))
            string username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

            //Exception thrown here:
            SPSite newSite = spfarmSite.SelfServiceCreateSite("http://myserver.com/sites/UnitTestSiteCol", "Unit test Site Col", 
                "Unit test Desc", 1033, 15, "STS#1",
                username, "Unit Test", "unit@test.com", null, null, null, null);

            //Act ...
            //Assert ...


I'm using MSTest in Visual Studio 2012 for SharePoint 2013 and have "Default Processor Architecture" set to X64

http://myserver.com/sites is a managed path

I tried using a user token but it didn't help:

        SPUserToken sysUserToken = null;
        using (SPSite tempSite = new SPSite("http://myserver.com"))
            sysUserToken = tempSite.SystemAccount.UserToken;
        using (SPSite spfarmSite = new SPSite("http://myserver.com", sysUserToken))

Adding RunWithElevatedPrivileges didn't help

  • What lines are failing in each example? – tyshock Dec 12 '13 at 21:30
  • SPSite newSite = spfarmSite.SelfServiceCreateSite – Daniel Dec 12 '13 at 21:30
  • 2
    Have you verified that 'username' is the value that you would expect during the unittest? – tyshock Dec 12 '13 at 21:38
  • You're correct, the difference is the user - The unit test is running as me, the web request version is running as NTAUTHORITY. Maybe I can impersonate during the unit test... – Daniel Dec 12 '13 at 22:19

It sounds like your process account does not have access to the SharePoint databases! Open a SharePoint Shell as administrator and use the Add-SPShellAdmin Cmdlet to grant your unit test process account full access to the SharePoint configuration database and the SharePoint content databases. Your code works in a SharePoint web context because the IIS Application Pool account has write access to the SharePoint content databases.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.