在TFS API中,我如何获得一个给定测试的完整类名?

问题描述 投票:3回答:4

我有一个 ITestCaseResult 对象在手,我却不知道如何从中提取测试类信息。对象中包含了测试方法的名称,在它的 TestCaseTitle 属性,但在我们的代码库中有很多重复的标题,我想了解更多信息。

假设我有 Foo.Bar 班组 Baz 和方法 ThisIsATestMethod目前,我只能访问 ThisIsATestMethod 的信息,但我想从标题中获得。Foo.Bar.Baz.ThisIsATestMethod.

如何使用TFS API来实现?

下面是一些简单的代码。

var def = buildServer.CreateBuildDetailSpec(teamProject.Name);
def.MaxBuildsPerDefinition = 1;
def.QueryOrder = BuildQueryOrder.FinishTimeDescending;
def.DefinitionSpec.Name = buildDefinition.Name;
def.Status = BuildStatus.Failed | BuildStatus.PartiallySucceeded | BuildStatus.Succeeded;

var build = buildServer.QueryBuilds(def).Builds.SingleOrDefault();
if (build == null)
    return;

var testRun = tms.GetTeamProject(teamProject.Name).TestRuns.ByBuild(build.Uri).SingleOrDefault();
if (testRun == null)
    return;

foreach (var outcome in new[] { TestOutcome.Error, TestOutcome.Failed, TestOutcome.Inconclusive, TestOutcome.Timeout, TestOutcome.Warning })
    ProcessTestResults(bd, testRun, outcome);

...

private void ProcessTestResults(ADBM.BuildDefinition bd, ITestRun testRun, TestOutcome outcome)
{
    var results = testRun.QueryResultsByOutcome(outcome);
    if (results.Count == 0)
        return;


    var testResults = from r in results // The "r" in here is an ITestCaseResult. r.GetTestCase() is always null.
                      select new ADBM.Test() { Title = r.TestCaseTitle, Outcome = outcome.ToString(), ErrorMessage = r.ErrorMessage };
}
c# .net tfs
4个回答
5
投票

你可以通过从TFS下载TRX文件,然后手动解析它。 要为测试运行下载TRX文件,请这样做。

    TfsTeamProjectCollection tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri("http://my-tfs:8080/tfs/DefaultCollection"));
    ITestManagementService tms = tpc.GetService<ITestManagementService>();
    ITestManagementTeamProject tmtp = tms.GetTeamProject("My Project");
    ITestRunHelper testRunHelper = tmtp.TestRuns;
    IEnumerable<ITestRun> testRuns = testRunHelper.ByBuild(new Uri("vstfs:///Build/Build/123456"));
    var failedRuns = testRuns.Where(run => run.QueryResultsByOutcome(TestOutcome.Failed).Any()).ToList();
    failedRuns.First().Attachments[0].DownloadToFile(@"D:\temp\myfile.trx");

然后解析TRX文件(是XML),寻找<TestMethod>元素,它在 "className "属性中包含完全限定的类名。

<TestMethod codeBase="C:/Builds/My.Test.AssemblyName.DLL" adapterTypeName="Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter, Microsoft.VisualStudio.QualityTools.Tips.UnitTest.Adapter, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" className="My.Test.ClassName, My.Test.AssemblyName, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" name="Test_Method" />

2
投票

由于测试用例的细节存储在工作项中,你可以通过访问测试用例的工作项来获取数据。

ITestCaseResult result;
var testCase = result.GetTestCase();
testCase.WorkItem["Automated Test Name"]; // fqdn of method
testCase.WorkItem["Automated Test Storage"]; // dll

2
投票

在这里,你有办法获得大会名称。

    foreach (ITestCaseResult testCaseResult in failures)
    {
        string testName = testCaseResult.TestCaseTitle;
        ITmiTestImplementation testImplementation = testCaseResult.Implementation as                 ITmiTestImplementation;
    string assembly = testImplementation.Storage;
    }

不幸的是: ITestCaseResultITmiTestImplementation 似乎不包含测试用例的命名空间。

检查最后一个响应,在 这个环节,这可能会有所帮助.祝你好运!

编辑: 这是基于 Charles Crain'的答案,但获取类名时不用下载到文件。

    var className = GetTestClassName(testResult.Attachments);

还有方法本身

    private static string GetTestClassName(IAttachmentCollection attachmentCol)
    {
        if (attachmentCol == null || attachmentCol.Count == 0)
        {
            return string.Empty;
        }

        var attachment = attachmentCol.First(att => att.AttachmentType == "TmiTestResultDetail");

        var content = new byte[attachment.Length];
        attachment.DownloadToArray(content, 0);
        var strContent = Encoding.UTF8.GetString(content);

        var reader = XmlReader.Create(new StringReader(RemoveTroublesomeCharacters(strContent)));
        var root = XElement.Load(reader);
        var nameTable = reader.NameTable;
        if (nameTable != null)
        {
            var namespaceManager = new XmlNamespaceManager(nameTable);
            namespaceManager.AddNamespace("ns", "http://microsoft.com/schemas/VisualStudio/TeamTest/2010");

            var classNameAtt = root.XPathSelectElement("./ns:TestDefinitions/ns:UnitTest[1]/ns:TestMethod[1]", namespaceManager).Attribute("className");

            if (classNameAtt != null) return classNameAtt.Value.Split(',')[1].Trim();
        }

        return string.Empty;
    }

    internal static string RemoveTroublesomeCharacters(string inString)
    {
        if (inString == null) return null;

        var newString = new StringBuilder();

        foreach (var ch in inString)
        {
            // remove any characters outside the valid UTF-8 range as well as all control characters
            // except tabs and new lines
            if ((ch < 0x00FD && ch > 0x001F) || ch == '\t' || ch == '\n' || ch == '\r')
            {
                newString.Append(ch);
            }
        }
        return newString.ToString();
    }

1
投票
public string GetFullyQualifiedName()
{
  var collection = new TfsTeamProjectCollection("http://tfstest:8080/tfs/DefaultCollection");
  var service = collection.GetService<ITestManagementService>();

  var tmProject = service.GetTeamProject(project.TeamProjectName);
  var testRuns = tmProject.TestRuns.Query("select * From TestRun").OrderByDescending(x => x.DateCompleted);

  var run = testRuns.First();

  var client = collection.GetClient<TestResultsHttpClient>();
  var Tests = client.GetTestResultsAsync(run.ProjectName, run.Id).Result;

  var FullyQualifiedName = Tests.First().AutomatedTestName;
  return FullyQualifiedName;
}
© www.soinside.com 2019 - 2024. All rights reserved.