首页 > 解决方案 > C# - Asp.net Web API 测试项目 - 如何模拟用户并在特定用户下运行测试用例

问题描述

我正在研究 ASP.net Web api 项目。我添加了一个测试项目。在其中一个测试用例中,我使用 Windows 身份验证连接到 SQL Server。当我在 Visual Studio 上运行测试用例时,它在本地运行良好,因为我的帐户(我的 NT ID)有权访问 SQL 服务器。

但是当我们在构建服务器上运行相同的测试用例时,测试用例失败了Microsoft.AnalysisServices.AdomdClient.AdomdErrorResponseException: Either the user, 'domain\ttwp5434203$', does not have access to the 'Employee' database, or the database does not exist.

为了克服这个问题,我正在考虑模拟运行测试用例的用户。

我在测试项目下的 App.Config 文件中添加了以下代码。

<system.web>
    <identity impersonate="true"
              userName="UID"
              password= "PWD" />
  </system.web>

这种改变没有奏效。我又遇到了同样的错误。我该怎么做才能确保任何机器上的测试用例在特定帐户下运行。

我希望使用的另一个选项是:Impersonate(IntPtr)。但我不确定如何在多个测试用例中使用此代码。

标签: c#.netasp.net-web-apimstestimpersonation

解决方案


我现在正在使用SimpleImpersonation库运行我的测试用例。这个 nugget 包允许你模拟一些用户并且它真的很容易使用。

 [TestMethod]
    public void SearchUser()
    {
        var  credentials = new UserCredentials("domain", "UID", "PWD");
        var result = Impersonation.RunAsUser(credentials, LogonType.NewCredentials, () =>
        {
            //CODE INSDIE THIS BLOCK WILL RUN UNDER THE ID OF ANOTHER USER 
            dynamic actualResult = controller.SearchUser();
            //Assert
            Assert.IsNotNull(actualResult);
            return actualResult;
        });
    }

推荐阅读