2014-10-06 115 views
1

我以前见过这个讨论过几次,我不确定这是否对我来说是最好的事情,所以有任何改进的建议都会受到欢迎。获取传递给方法的变量的声明名称C#

我想为我的Selenium测试建立一些详细的日志记录。

我有一个方法调用,它是:

Admin_Login.Username.SetText("MyUsername"); 

Admin_Login仅仅是一个标准的类。但是“用户名”是传递到“的setText”方法的变量,如下图所示:

public static void SetText(this By identifier, string value) 
{ 
    StackTrace stackTrace = new StackTrace(); 
    string methodName = stackTrace.GetFrame(1).GetMethod().Name; 
    string className = stackTrace.GetFrame(1).GetMethod().DeclaringType.FullName; 


    //I do some logging here for the manual testers so they can debug after a run 
    TestDriver.ResultsLog.LogComment("Class: " + className); 
    TestDriver.ResultsLog.LogComment("Calling Method: " + methodName); 
    TestDriver.ResultsLog.LogComment("Calling Element: " + identifier.toString()); 

    IWebElement element = WebDriver.driver.FindElementSafe(identifier); 
    ((IJavaScriptExecutor)WebDriver.driver).ExecuteScript("arguments[0].value = arguments[1]", element, value); 
} 

以供参考,在这里是管理类:

public class Admin_Login 
{ 
    public static By Username = By.Id("ctl00_MainContent_ctlLoginView_ctlLogin_UserName"); 
} 

所以我可以登录类名和方法名称很好,但我需要找到的是传入方法的“标识符”变量的声明名称。

所以在这种情况下,值应该是“用户名”。

我已经尝试了一些建议,产生标识符的名称作为“标识符”,但这真的不是我想要的。我需要知道哪个对象的SetText方法被关闭,如果这是有道理的。

正如我所说,也许我不会这样做的正确方式,所以任何建议都会有所帮助。

+0

这也有助于有什么用“手动测试人员“?如果他们有权访问调试器并希望使用调试器,他们应该使用它。 – Arran 2014-10-06 16:32:23

+0

手动测试人员不是编码人员,因此他们将分析HTML结果日志,告诉他们测试失败的原因以及原因。这样他们就可以向自动化团队或其团队中的开发人员报告。 他们不希望使用调试器。 调试不一定要使用物理调试器工具:) – Festivejelly 2014-10-08 08:24:16

回答

1

我不能相信我居然建议,因为该解决方案有多脏这个......但,这是一个解决方案... ... SOOOOO

class Program 
{ 
    static void Main() 
    { 
     var foo = new Foo(); 
     var bar = foo; 

     foo.Hit(); 
     bar.Hit(); 
    } 
} 

public static class Extensions 
{ 
    public static void Hit(this Foo foo, [CallerMemberName] string name = null, [CallerFilePath] string path = null, [CallerLineNumber] int lineNumber = -1) 
    { 
     string callerVariableName; 

     using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) 
     { 
      StreamReader reader = new StreamReader(stream); 
      string csharpFile = reader.ReadToEnd(); 
      string[] lines = csharpFile.Split('\n'); 
      string callingLine = lines[lineNumber - 1]; 

      Match matchVariableName = Regex.Match(callingLine, @"([a-zA-Z]+[^\.]*)\.Hit\(\)"); 

      callerVariableName = matchVariableName.Groups[1].Value; 
     } 

     Console.WriteLine("\n///////////////////////////////"); 
     Console.WriteLine("Caller method name: {0}", name); 
     Console.WriteLine("Caller variable name: {0}", callerVariableName); 
     Console.WriteLine("File Path:   {0}", path); 
     Console.WriteLine("Line number:   {0}", lineNumber); 

    } 
} 

public class Foo 
{ 
} 
+0

谢谢艾登,我会试试看。 有时候肮脏的解决方案是独特的问题需要! :) – Festivejelly 2014-10-06 07:32:15

+0

这似乎为我工作。我只是想知道这是否会运行在本地机器运行单元测试通过DLL,因为它不会有权访问C#文件? – Festivejelly 2014-10-06 08:15:14