使用不同的凭据运行NUnit集成测试

Arn*_*und 5 c# sql-server impersonation nunit unit-testing

我正在使用C#,NUnit和SQL Server 2008 r2 dev版数据库运行集成测试.设置我的夹具包括创建一个新数据库和加载测试数据,所以我需要dbo权限.

但是,我希望以较少的权限运行测试.我有另一个我可以通过身份验证的AD帐户,我可以使用模拟运行一些T-SQL ,如下所述:http://support.microsoft.com/?scid = 306158,如下所示:

public static bool ExecuteFileAs(string fileName, string connectionString, 
                                  string user, string domain, string password)
{
    using(new Impersonator(user, domain, password))
    {
        using(var connection = new SqlConnection(connectionString))
        {
            connection.Open();
            return SqlFileExecuter.RunSql(connection, fileName);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我点击此代码段内的断点并启动Profiler时,我看到另一个连接以我提交给它的用户名打开,因此模拟确实有效.不幸的是,我无法在夹具设置结束时运行所有模拟测试,并在夹具拆卸时结束它.在设置结束时,我执行以下操作:

        impersonator = new Impersonator("username", "DOMAIN", "pwd");
Run Code Online (Sandbox Code Playgroud)

第一次单元测试开始后,我收到此错误列出了此测试中使用的一个dll:System.IO.FileLoadException: Could not load file or assembly '...' or one of its dependencies. Access is denied. 我已经授予其他帐户完全访问该目录的所有二进制文件,这没有帮助.

欢迎任何建议.

编辑:我的工作站仍在运行XP.

Tra*_*vis 3

一种可能的解决方案是不使用 Windows 身份验证,而使用 SQL 用户。这只是连接字符串的更改。

此外,如果错误与 IO 权限相关,您可以在模拟用户之前尝试执行所有 IO。使用http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.server.aspx可以直接SqlFileExecuter对 SQL Server 执行 T-SQL 块(与 ADO.NET 不同)。SMO 与上面的做法略有不同......

var s = new Server(connectionString);
s.ConnectionContext.ExecuteNonQuery(@"CREATE DATABASE test; GO; Use test; ...");
Run Code Online (Sandbox Code Playgroud)