C# - Asp.net Web API 测试项目 - 如何模拟用户并在特定用户下运行测试用例



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

但是当我们在构建服务器上运行相同的测试用例时,测试用例失败,说Microsoft.AnalysisServices.AdomdClient.AdomdErrorResponseException: Either the user, 'domainttwp5434203$', 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(。但我不确定如何在多个测试用例中使用此代码。

我现在正在使用简单模拟库运行我的测试用例。这个 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;
});
}

最新更新