none
How to execute test methods programmatically using C# (may be using reflection)? RRS feed

  • Question

  • I have a unit test project for UI automation using selenium web driver. I can execute test from visual studio and even from command line. I am trying to execute test methods in the unit test project using C#. I tried to use reflection and load the test assemblies and then call the test method by its full name. But it didnt work as test methods seems to be special kind of methods. How can i run the test methods using reflection? If there is a better way other than reflection then please let me know.

    Also, we have config file with name <<test assembly name>>.config and i am having a key in this config file for running UI test on a specific browser. So, when i am discovering and executing test methods pro grammatically i would like first change the browser in the config file and then execute test method.


    Thanks, Pratap

    Wednesday, November 1, 2017 2:44 AM

Answers

  • Hi Fletcher,

    Sorry for coming back here so late. I have found the solution that suits my need. As it can help others with same problem, i am putting my solution here.

    I am using the UnitTestRunner that MSTestFramework offers (this can found in Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll). Below is a sample code how to execute the testmethod from assembly.

    You will need to add below references

    1. Microsoft.VisualStudio.TestPlatform.ObjectModel.dll located at "Visual_Studio_Directory\Common7\IDE\CommonExtensions\Microsoft\TestWindow"

    2. Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll located at "Visual_Studio_Directory\Common7\IDE\CommonExtensions\Microsoft\TestWindow\Extensions"

    First you will need to deploy the items like dlls, test data, configs file, etc. Below is the method for doing that.

            string DeployItems(string source)
            {
                string deploymentPath = Path.Combine(GetTempFolderPath(), "TestRunner");
                if (Directory.Exists(deploymentPath) == false)
                    Directory.CreateDirectory(deploymentPath);
    
                DateTime dt = DateTime.Now;
                string dirName = string.Format("Deploy_{0} {1}-{2}-{3} {4}_{5}_{6}_{7}", Environment.UserName, dt.Day.ToString(), dt.Month.ToString(), dt.Year.ToString(),
                    dt.Hour.ToString(), dt.Minute.ToString(), dt.Second.ToString(), dt.Millisecond.ToString());
    
                DirectoryInfo dirInfo = Directory.CreateDirectory(Path.Combine(deploymentPath, dirName));
                DirectoryInfo dirIn = Directory.CreateDirectory(Path.Combine(dirInfo.FullName, "In"));
                Directory.CreateDirectory(Path.Combine(dirIn.FullName, Environment.MachineName));
                DirectoryInfo dirOut = Directory.CreateDirectory(Path.Combine(dirInfo.FullName, "Out"));
    
                Microsoft.VisualBasic.Devices.Computer comp = new Microsoft.VisualBasic.Devices.Computer();
                comp.FileSystem.CopyDirectory(source, dirOut.FullName);
    
                return dirInfo.FullName;
            }

    Below is the code for running the test method.

    string deploymentPath = DeployItems("Source directory containing the assemblies");
    
    string dllName = "Name_Assembly_ThatHas_TestMethods";
    string nameOfTestClass = "NameOfTestClassThatHasTestMethod";
    string nameOfTestMethod = "NameOfTestMethodThatWeWantToRun";
    
    UnitTestRunner testRunner = new UnitTestRunner(deploymentPath, dllName, false);
    
    // Set the test run properties
    Dictionary<string, object> properties = PrepareTestRunProperties(deploymentPath, nameOfTestClass, nameOfTestMethod);
    
    TestMethod testMethod = new TestMethod(nameOfTestMethod, nameOfTestClass, dllName, false);
    UnitTestElement testElement = new UnitTestElement(testMethod);
    UnitTestResult[] testResults = testRunner.RunDataDrivenTest(nameOfTestMethod, nameOfTestClass, false, properties);
    
    if (testResults[0].Outcome == UnitTestOutcome.Passed)
    {
     Console.WriteLine("Test Case Passed");
    }
    else
    {
     Console.WriteLine("Test Case Failed with error " + testResults[0].ErrorMessage);
    }

    Below is the method for preparing the test run properties.

    Dictionary<string, object> PrepareTestRunProperties(string deploymentPath, string nameOfTestClass, string nameOfTestMethod)
    {
     Dictionary<string, object> properties = new 
     Dictionary<string, object>(); 
     properties.Add("TestRunDirectory", deploymentPath);
     properties.Add("DeploymentDirectory", 
     Path.Combine(deploymentPath, "Out"));
     properties.Add("ResultsDirectory", 
     Path.Combine(deploymentPath, "In"));
     properties.Add("TestRunResultsDirectory", 
     Path.Combine(deploymentPath, "In", 
     Environment.MachineName));
     properties.Add("TestResultsDirectory", 
     Path.Combine(deploymentPath, "In"));
     properties.Add("TestDir", Path.Combine(deploymentPath));
     properties.Add("TestDeploymentDir", 
     Path.Combine(deploymentPath, "Out"));
     properties.Add("TestLogsDir", Path.Combine(deploymentPath, 
     "In", Environment.MachineName));
     properties.Add("FullyQualifiedTestClassName", 
     nameOfTestClass);
     properties.Add("TestName", nameOfTestMethod);
     return properties;
     }

    Also, you will need to set the current directory to the deployed directory that has the test assemblies and the dependent files including other assemblies. We can set current directory Directory.SetCurrentDirectory method. With this it will be easier for the MSTest framework to locate the test data that we are defining on the test method using DataSource attribute.


    Thanks, Pratap

    • Proposed as answer by Fletch Zhou Thursday, November 23, 2017 3:10 AM
    • Marked as answer by Pratap15 Thursday, November 23, 2017 11:43 AM
    Tuesday, November 21, 2017 12:47 PM

All replies

  • Hi Pratap,

    First, thank you for you posting.

    Normally, we use Coded UI test in VS to run UI automation.

    To use reflection to load the test assemblies, I found two threads which might be useful, you may to the links below:

    https://stackoverflow.com/questions/14479074/c-sharp-reflection-load-assembly-and-invoke-a-method-if-it-exists

    https://stackoverflow.com/questions/2202381/reflection-how-to-invoke-method-with-parameters

    Your understanding and cooperation will be grateful:)

      

    Best regards,

    Fletcher


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.



    • Edited by Fletch Zhou Thursday, November 2, 2017 5:54 AM
    Thursday, November 2, 2017 5:52 AM
  • Hi Fletcher,

    Thanks for your reply.

    I followed the stackoverflow post that you provided. But it is not giving the result that i expected. I have base class with attribute TestClass which has the TestInitialize method. I am inheriting this base class but when i am calling one of my test method as below

    string dllPath = @"Path_of_test_assembly";

    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; Assembly testAssembly = Assembly.LoadFile(dllPath); Type testClass = testAssembly.GetType("MySampleTest.RegressionSuite"); MethodInfo mInfo = testClass.GetMethod("TC00000_SampleTest"); var instance = Activator.CreateInstance(testClass); object result = mInfo.Invoke(instance, null); The Invoke method call is calling the test method but the browser is not getting launched and TestInitialize is where the browser is opened and navigates to the login url. What i am missing here?



    Thanks, Pratap


    • Edited by Pratap15 Thursday, November 2, 2017 11:54 AM
    Thursday, November 2, 2017 11:54 AM
  • Hi Pratap15,

    Thank you for posting here.

    For your question, if you want to use reflection, here is a simple example for your reference.

    ClassLibrary.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ClassLibrary2
    {
        public class Class1
        {
            public static string Method1(string s)
            {
                return "Method1" + s;
            }
          
        }
    }

    C# CODE.

            static void Main(string[] args)
            {
               Assembly assembly = Assembly.LoadFrom(@"D:\Visual Studio Projects\ConsoleApp\ClassLibrary2\bin\Debug\ClassLibrary2.dll");         
                Type type = assembly.GetType("ClassLibrary2.Class1");
                object instance = assembly.CreateInstance("ClassLibrary2.Class1");
                Type[] params_type = new Type[1];
                params_type[0] = Type.GetType("System.String");
               
                Object[] params_obj = new Object[1];
                params_obj[0] = "hello"; 
                object value = type.GetMethod("Method1", params_type).Invoke(instance, params_obj);
                Console.ReadKey();
            }

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Friday, November 3, 2017 8:58 AM
  • Hi Wendy,

    Reflection works perfectly in the code you provided. But problems comes when using reflection with unit tests. Below is a sample unit test with one test method that searches for some text in Google.

    using System;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using OpenQA.Selenium;
    using System.Configuration;
    using OpenQA.Selenium.Chrome;
    using OpenQA.Selenium.Firefox;
    using OpenQA.Selenium.IE;
    
    namespace SampleTestForReflection
    {
        [TestClass]
        public class MyTest : BaseTestClass
        {
            [TestMethod]
            [DeploymentItem(@"TestData.xml")]
            [DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML", "|DataDirectory|\\TestData.xml", "MyTestData", DataAccessMethod.Sequential)]
            public void TEST_SearchMSDNForumInGoogle()
            {
                _driver.Navigate().GoToUrl("http://www.google.com");
                string valueToSearch = TestContext.DataRow["GoogleSearch"].ToString();
                IWebElement textBox_Search = _driver.FindElement(By.Name("q"));
                textBox_Search.SendKeys(valueToSearch);
                IWebElement btnSearch = _driver.FindElement(By.Name("btnK"));
                btnSearch.Click();
            }
        }
    }

    The MyTest class is inheriting the BaseTestClass which is again a unit test and BaseTestClass is shown below.

    using System;
    using System.Text;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System.Configuration;
    using OpenQA.Selenium.Chrome;
    using OpenQA.Selenium;
    using OpenQA.Selenium.Firefox;
    using OpenQA.Selenium.IE;
    
    namespace SampleTestForReflection
    {
        /// <summary>
        /// Summary description for BaseTestClass
        /// </summary>
        [TestClass]
        public class BaseTestClass
        {
            protected IWebDriver _driver = null;
    
            public BaseTestClass()
            {
            }
    
            private TestContext testContextInstance;
    
            /// <summary>
            ///Gets or sets the test context which provides
            ///information about and functionality for the current test run.
            ///</summary>
            public TestContext TestContext
            {
                get
                {
                    return testContextInstance;
                }
                set
                {
                    testContextInstance = value;
                }
            }
    
            [TestInitialize]
            public void MyTestInitialize()
            {
                string browser = ConfigurationManager.AppSettings["Browser"];
                switch (browser.ToLower())
                {
                    case "chrome":
                        _driver = new ChromeDriver();
                        break;
                    case "firefox":
                        _driver = new FirefoxDriver();
                        break;
                    case "internet explorer":
                    case "ie":
                        _driver = new InternetExplorerDriver();
                        break;
                    default:
                        throw new ArgumentException("Unknown browser " + browser);
                }
    
                _driver.Manage().Window.Maximize();
            }
    
            [TestCleanup]
            public void MyTestCleanUp()
            {
                if (_driver != null)
                    _driver.Dispose();
            }
        }
    }

    Then in my console app, i am tying to invoke the TestInit method (which initialize the web driver and this works perfectly) then i am trying to invoke the TestMethod as below.

                Configuration originalConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                // Here, i am setting the browser of my choice
                originalConfig.AppSettings.Settings.Add("Browser", "Chrome");
                originalConfig.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
    
                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
    
                string test = ConfigurationManager.AppSettings["Browser"];
    
                Assembly myAssembly = Assembly.LoadFrom(dllPath);
    
                Type testClass = myAssembly.GetType("SampleTestForReflection.MyTest");
                object objTestClass = myAssembly.CreateInstance("SampleTestForReflection.MyTest");
                MethodInfo mInfo = testClass.GetMethod("TEST_SearchMSDNForumInGoogle");
                MethodInfo testInit = testClass.GetMethod("MyTestInitialize");
                PropertyInfo testContext = testClass.GetProperty("TestContext");
                var allProps = testClass.GetProperties();
                testInit.Invoke(objTestClass, null);
                object result = mInfo.Invoke(objTestClass, null);

    The error comes when it comes to TestContext that reads the data from data source as below. The error is NullReferenceException as the TestContext is not initialized.

                string valueToSearch = TestContext.DataRow["GoogleSearch"].ToString();

    How can i initialize the TestContext? I know this object automatically get initialized by MS test framework but i cannot find a way to set it using reflection.


    Thanks, Pratap


    • Edited by Pratap15 Sunday, November 5, 2017 3:01 AM
    Sunday, November 5, 2017 3:01 AM
  • Hi Pratap,

    >>How can i initialize the TestContext? I know this object automatically get initialized by MS test framework but i cannot find a way to set it using reflection.

     Please refer to the thread below to see if it could help, which is also related to read context issue:

    https://stackoverflow.com/questions/29868852/setting-a-field-of-a-classs-instance-with-reflection

    Hope it helps. 

     

    Best regards,

    Fletcher


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    • Edited by Fletch Zhou Monday, November 6, 2017 9:32 AM
    Monday, November 6, 2017 9:32 AM
  • Hi Fletcher,

    Thanks for your help.

    The problem that i am facing is with TestContext. If we execute test from Visual Studio, TestContext is automatically set. Using the link that you provided, i tried to set the TestContext using reflection but it did not give expected result.

    Here is the complete code that i am using for executing the test method (in unit test project) through reflection. I have put the code for setting the TestContext within a region.

        class Program
        {
            static void Main(string[] args)
            {
                string dllPath = @"C:\Tutorial\C#\SampleTestForReflection\SampleTestForReflection\bin\Debug\SampleTestForReflection.dll";
                string nameOfTestClass = "SampleTestForReflection.MyTest";
                string nameOfTestMethod = "TEST_SearchMSDNForumInGoogle";
                string testRootDirectory = @"C:\Tutorial\C#\SampleTestForReflection\TestResults";
    
                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
    
                Configuration originalConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                originalConfig.AppSettings.Settings.Add("Browser", "Chrome");
                originalConfig.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
    
                Assembly testAssembly = Assembly.LoadFile(dllPath);
                Type testClass = testAssembly.GetType(nameOfTestClass);
                object instanceOfTestClass = testAssembly.CreateInstance(nameOfTestClass);
    
                // Create Deployment folder and copy files to Out folder
                CopyFiles(new FileInfo(dllPath).Directory.FullName, testRootDirectory);
    
                #region Intializing the objects which are needed for setting the TestContext
    
                TestMethod _testMethod = new TestMethod(nameOfTestMethod, nameOfTestClass, dllPath, false);
                IDictionary<string, object> properties = new Dictionary<string, object>()
                {
                    { "FullyQualifiedTestClassName", nameOfTestClass },
                    { "TestName", nameOfTestMethod }
                };
                TestRunDirectories testRunDir = new TestRunDirectories(testRootDirectory);
                ThreadSafeStringWriter strWriter = new ThreadSafeStringWriter(System.Globalization.CultureInfo.InvariantCulture);
                TestContextImplementation tci = new TestContextImplementation(_testMethod, strWriter, properties, testRunDir);
    
                PropertyInfo propTestContext = testClass.GetProperty("TestContext");
                propTestContext.SetValue(instanceOfTestClass, tci);
    
                #endregion
    
                MethodInfo testInit = testClass.GetMethod("MyTestInitialize");
                MethodInfo testMethod = testClass.GetMethod(nameOfTestMethod);
    
                object resTestInit = testInit.Invoke(instanceOfTestClass, null);
                PropertyInfo testContextField = testClass.GetProperty("TestContext");
    
                // I am getting the value of TestContext but it did not give correct as the correct (may be all) data was not set
                object valueOfTestContext = testContextField.GetValue(instanceOfTestClass);
                object test = testContextField.GetMethod.Invoke(instanceOfTestClass, null);
                object resTestMethod = testMethod.Invoke(instanceOfTestClass, null);
    
                Console.WriteLine("Press ENTER to exit");
                Console.ReadLine();
            }
    
            static void CopyFiles(string source, string destination)
            {
                DateTime dt = DateTime.Now;
                string dirName = string.Format("Deploy_{0} {1}-{2}-{3} {4}_{5}_{6}", Environment.UserName, dt.Day.ToString(), dt.Month.ToString(), dt.Year.ToString(),
                    dt.Hour.ToString(), dt.Minute.ToString(), dt.Second.ToString());
    
                DirectoryInfo dirInfo = Directory.CreateDirectory(Path.Combine(destination, dirName));
                DirectoryInfo dirIn = Directory.CreateDirectory(Path.Combine(dirInfo.FullName, "In"));
                Directory.CreateDirectory(Path.Combine(dirIn.FullName, Environment.MachineName));
                DirectoryInfo dirOut = Directory.CreateDirectory(Path.Combine(dirInfo.FullName, "Out"));
    
                string[] files = Directory.GetFiles(source);
                foreach (string item in files)
                {
                    File.Copy(item, dirOut.FullName + "\\" + new FileInfo(item).Name);
                }
            }
    
            static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
            {
                string pathOfParentDirectory = new FileInfo(args.RequestingAssembly.Location).Directory.FullName;
                string dependentDllPath = Path.Combine(pathOfParentDirectory, args.Name.Remove(args.Name.IndexOf(',')) + ".dll");
    
                if (File.Exists(dependentDllPath) == false)
                    throw new FileNotFoundException(dependentDllPath);
    
                return Assembly.LoadFile(dependentDllPath);
            }
        }

    Below is the value of TestContext that i have set in the above code (the CurrentTestOutcome is showing Failed instead of InProcess and DataRow is null)

    If i run the same test method from visual studio, the value of TestContext is shown below

    How can i set the TestContext correctly so that it uses the data file mentioned in DataSource attribute of the test method and to show the correct status of the test execution?


    Thanks, Pratap

    Tuesday, November 7, 2017 1:35 AM
  • Hi Fletcher,

    Sorry for coming back here so late. I have found the solution that suits my need. As it can help others with same problem, i am putting my solution here.

    I am using the UnitTestRunner that MSTestFramework offers (this can found in Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll). Below is a sample code how to execute the testmethod from assembly.

    You will need to add below references

    1. Microsoft.VisualStudio.TestPlatform.ObjectModel.dll located at "Visual_Studio_Directory\Common7\IDE\CommonExtensions\Microsoft\TestWindow"

    2. Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll located at "Visual_Studio_Directory\Common7\IDE\CommonExtensions\Microsoft\TestWindow\Extensions"

    First you will need to deploy the items like dlls, test data, configs file, etc. Below is the method for doing that.

            string DeployItems(string source)
            {
                string deploymentPath = Path.Combine(GetTempFolderPath(), "TestRunner");
                if (Directory.Exists(deploymentPath) == false)
                    Directory.CreateDirectory(deploymentPath);
    
                DateTime dt = DateTime.Now;
                string dirName = string.Format("Deploy_{0} {1}-{2}-{3} {4}_{5}_{6}_{7}", Environment.UserName, dt.Day.ToString(), dt.Month.ToString(), dt.Year.ToString(),
                    dt.Hour.ToString(), dt.Minute.ToString(), dt.Second.ToString(), dt.Millisecond.ToString());
    
                DirectoryInfo dirInfo = Directory.CreateDirectory(Path.Combine(deploymentPath, dirName));
                DirectoryInfo dirIn = Directory.CreateDirectory(Path.Combine(dirInfo.FullName, "In"));
                Directory.CreateDirectory(Path.Combine(dirIn.FullName, Environment.MachineName));
                DirectoryInfo dirOut = Directory.CreateDirectory(Path.Combine(dirInfo.FullName, "Out"));
    
                Microsoft.VisualBasic.Devices.Computer comp = new Microsoft.VisualBasic.Devices.Computer();
                comp.FileSystem.CopyDirectory(source, dirOut.FullName);
    
                return dirInfo.FullName;
            }

    Below is the code for running the test method.

    string deploymentPath = DeployItems("Source directory containing the assemblies");
    
    string dllName = "Name_Assembly_ThatHas_TestMethods";
    string nameOfTestClass = "NameOfTestClassThatHasTestMethod";
    string nameOfTestMethod = "NameOfTestMethodThatWeWantToRun";
    
    UnitTestRunner testRunner = new UnitTestRunner(deploymentPath, dllName, false);
    
    // Set the test run properties
    Dictionary<string, object> properties = PrepareTestRunProperties(deploymentPath, nameOfTestClass, nameOfTestMethod);
    
    TestMethod testMethod = new TestMethod(nameOfTestMethod, nameOfTestClass, dllName, false);
    UnitTestElement testElement = new UnitTestElement(testMethod);
    UnitTestResult[] testResults = testRunner.RunDataDrivenTest(nameOfTestMethod, nameOfTestClass, false, properties);
    
    if (testResults[0].Outcome == UnitTestOutcome.Passed)
    {
     Console.WriteLine("Test Case Passed");
    }
    else
    {
     Console.WriteLine("Test Case Failed with error " + testResults[0].ErrorMessage);
    }

    Below is the method for preparing the test run properties.

    Dictionary<string, object> PrepareTestRunProperties(string deploymentPath, string nameOfTestClass, string nameOfTestMethod)
    {
     Dictionary<string, object> properties = new 
     Dictionary<string, object>(); 
     properties.Add("TestRunDirectory", deploymentPath);
     properties.Add("DeploymentDirectory", 
     Path.Combine(deploymentPath, "Out"));
     properties.Add("ResultsDirectory", 
     Path.Combine(deploymentPath, "In"));
     properties.Add("TestRunResultsDirectory", 
     Path.Combine(deploymentPath, "In", 
     Environment.MachineName));
     properties.Add("TestResultsDirectory", 
     Path.Combine(deploymentPath, "In"));
     properties.Add("TestDir", Path.Combine(deploymentPath));
     properties.Add("TestDeploymentDir", 
     Path.Combine(deploymentPath, "Out"));
     properties.Add("TestLogsDir", Path.Combine(deploymentPath, 
     "In", Environment.MachineName));
     properties.Add("FullyQualifiedTestClassName", 
     nameOfTestClass);
     properties.Add("TestName", nameOfTestMethod);
     return properties;
     }

    Also, you will need to set the current directory to the deployed directory that has the test assemblies and the dependent files including other assemblies. We can set current directory Directory.SetCurrentDirectory method. With this it will be easier for the MSTest framework to locate the test data that we are defining on the test method using DataSource attribute.


    Thanks, Pratap

    • Proposed as answer by Fletch Zhou Thursday, November 23, 2017 3:10 AM
    • Marked as answer by Pratap15 Thursday, November 23, 2017 11:43 AM
    Tuesday, November 21, 2017 12:47 PM
  • Hi Pratap,

    So glad that your issue has been resolved.

    Please mark your own reply as answer if it's ok for you.

    Thanks for your contribution to our community.

     

    Regards,

    Fletcher


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    • Edited by Fletch Zhou Wednesday, November 22, 2017 2:06 AM
    Wednesday, November 22, 2017 2:06 AM
  • Hi Pratap 

    I am also trying to to the same thing, wherein I want to execute my test cases from a custom UI, I tried the above code but it doesn't work for me. 

    For 

    string deploymentPath = DeployItems("Source directory containing the assemblies");

    I am giving debug folder path, is it right.

    Thursday, February 15, 2018 4:41 AM
  • Hi Pratap, First thanks for sharing the code of Reflection for Automation.I used the same code in my console application to invoke the Coded UI TestMethod which I had prepared in the separate project.

    However, I am getting an error to invoke the <g class="gr_ gr_150 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="150" id="150">testmethod</g> in a console application with Reflection.

    Please refer the attached Stack Message for ErrorAdded dll in console appscreenshot of Stack Message & reference <g class="gr_ gr_291 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="291" id="291">dll</g> added into a Console application.

    Please let me know if I missed anything in it.

    Wednesday, March 21, 2018 12:39 PM
  • Hi All,

    I am able to execute MyIitialize, TestMethods & MyCleanUp with reflection with correcting the existing code shown in the earlier screenshots. However, I am not getting htmlLogs of test execution with this approach as in reflection, MSTestFramework is used & in Coded UI UnitTestFramework is used for execution.

    Can anyone plz help me on this issue?

    Friday, March 30, 2018 12:29 PM
  • Hello Pratap

    I am trying to make Data Driven test but no success.
    I only succeeded in running RunSingleTest by using UnitTestRunner, without using TestContext.

    Would you be kind to give me a test example of test class with data driven test and TestContext.
    When i am trying to run data driven tests i recive an error, "TestContext has incorrect type"
    And it would mean a lot if you could share which dll's and it's versions are you using in TestProject and TestRunnerProject.

    I am trying to figure this out for quite some time and it would mean a lot if you could give a helping hand.

    Thanks in advance
    AcoNes

    Wednesday, June 20, 2018 1:07 PM
  • I cannot find the diretory . I am using Visual Studion 2017

    Friday, July 5, 2019 1:04 AM