VSOnline自动化测试运行/构建与本地不同?

时间:2015-05-15 15:06:13

标签: unit-testing msbuild azure-devops

我有单元测试,通过确定项目路径来查找特定文件夹中的配置文件:

/// <summary>
/// Gets the project path of the given type. 
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static string GetProjectPath(Type type)
{
    var dll = new FileInfo(type.Assembly.Location);
    if (dll.Directory == null || // ...\Solution\Project\bin\Build 
        dll.Directory.Parent == null || // ...\Solution\Project\bin
        dll.Directory.Parent.Parent == null || // ...\Solution\Project
        dll.Directory.Parent.Parent.Parent == null) // ...\Solution
    {
        throw new Exception("Unable to find Project Path for " + type.FullName);
    }

    // Class Name, Project Name, Version, Culture, PublicKeyTyoken
    // ReSharper disable once PossibleNullReferenceException
    var projectName = type.AssemblyQualifiedName.Split(',')[1].Trim();
    var projectPath = Path.Combine(dll.Directory.Parent.Parent.Parent.FullName, projectName);

    if (!Directory.Exists(projectPath))
    {
        throw new Exception(String.Format("Unable to find Project Path for {0} at {1}", type.FullName, projectPath));  
    }

    return projectPath;
}

这在开发机器上很有用,但是当VSOnline Build启动时,单元测试失败,说它无法找到项目路径。这让我相信VSOnline在一台机器上构建,在另一台机器上进行单元测试,或者它的目录结构有些不同,或者单元测试没有读取文件系统的权限......

任何人都可以了解可能出现的问题?

1 个答案:

答案 0 :(得分:0)

当VSOnline执行构建时,源文件位于c:\a\src\Branch Name\,但在构建时,它会构建到c:\a\bin文件夹。我猜这是为了帮助减少任何长路径名错误。构建在同一台服务器上执行,但输出与在本地运行它不同。

这需要我的方法GetProjectPath方法中的一些更改:

string solutionFolder = null;

if (dll.Directory == null || // ...\Solution\Project\bin\Build 
    dll.Directory.Parent == null || // ...\Solution\Project\bin
    dll.Directory.Parent.Parent == null || // ...\Solution\Project
    dll.Directory.Parent.Parent.Parent == null) // ...\Solution
{
    if (dll.DirectoryName == @"C:\a\bin")
    {
        // Build is on VSOnline.  Redirect to other c:\a\src\Branch Name
        var s = new System.Diagnostics.StackTrace(true);
        for (var i = 0; i < s.FrameCount; i++)
        {
            var fileName = s.GetFrame(i).GetFileName();
            if (!String.IsNullOrEmpty(fileName))
            {
                // File name will be in the form of c:\a\src\Branch Name\project\filename.  Get everything up to and including the Branch Name
                var parts = fileName.Split(Path.DirectorySeparatorChar);
                solutionFolder = Path.Combine(parts[0] + Path.DirectorySeparatorChar + parts[1], parts[2], parts[3]);
                break;
            }
        }
    }

    if (String.IsNullOrWhiteSpace(solutionFolder))
    {
        throw new Exception("Unable to find Project Path for " + type.FullName + ".  Assembly Located at " + type.Assembly.Location + sb);
    }
}
else
{
    solutionFolder = dll.Directory.Parent.Parent.Parent.FullName;
}