Best Vstest code snippet using Microsoft.VisualStudio.TestPlatform.Client.DesignMode.DesignModeClient.TestRunMessageHandler
DesignModeClientTests.cs
Source:DesignModeClientTests.cs  
...52            DesignModeClient.Initialize();53            Assert.IsNotNull(DesignModeClient.Instance);54        }55        [TestMethod]56        public void TestRunMessageHandlerShouldCallCommmunicationManagerIfMessageisError()57        {58            this.mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny<string>()));59            this.designModeClient.TestRunMessageHandler(new object(), new TestRunMessageEventArgs(TestMessageLevel.Error, "message"));60            this.mockCommunicationManager.Verify(cm => cm.SendMessage(It.IsAny<string>(),It.IsAny<TestMessagePayload>()), Times.Once());61        }62        [TestMethod]63        public void TestRunMessageHandlerShouldCallCommmunicationManagerIfMessageisWarning()64        {65            this.mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny<string>()));66            this.designModeClient.TestRunMessageHandler(new object(), new TestRunMessageEventArgs(TestMessageLevel.Warning, "message"));67            this.mockCommunicationManager.Verify(cm => cm.SendMessage(It.IsAny<string>(), It.IsAny<TestMessagePayload>()), Times.Once());68        }69        [TestMethod]70        public void TestRunMessageHandlerShouldNotCallCommmunicationManagerIfMessageisInformational()71        {72            this.mockCommunicationManager.Setup(cm => cm.SendMessage(It.IsAny<string>()));73            this.designModeClient.TestRunMessageHandler(new object(), new TestRunMessageEventArgs(TestMessageLevel.Informational, "message"));74            this.mockCommunicationManager.Verify(cm => cm.SendMessage(It.IsAny<string>(), It.IsAny<TestMessagePayload>()), Times.Never());75        }76        [TestMethod]77        public void DesignModeClientConnectShouldSetupChannel()78        {79            var verCheck = new Message { MessageType = MessageType.VersionCheck, Payload = this.protocolVersion };80            var sessionEnd = new Message { MessageType = MessageType.SessionEnd };81            this.mockCommunicationManager.Setup(cm => cm.WaitForServerConnection(It.IsAny<int>())).Returns(true);82            this.mockCommunicationManager.SetupSequence(cm => cm.ReceiveMessage()).Returns(verCheck).Returns(sessionEnd);83            this.designModeClient.ConnectToClientAndProcessRequests(PortNumber, this.mockTestRequestManager.Object);84            this.mockCommunicationManager.Verify(cm => cm.SetupClientAsync(new IPEndPoint(IPAddress.Loopback, PortNumber)), Times.Once);85            this.mockCommunicationManager.Verify(cm => cm.WaitForServerConnection(It.IsAny<int>()), Times.Once);86            this.mockCommunicationManager.Verify(cm => cm.SendMessage(MessageType.SessionConnected), Times.Once());87            this.mockCommunicationManager.Verify(cm => cm.SendMessage(MessageType.VersionCheck, this.protocolVersion), Times.Once());...DesignModeClient.cs
Source:DesignModeClient.cs  
...62            this.communicationManager = communicationManager;63            this.dataSerializer = dataSerializer;64            this.platformEnvironment = platformEnvironment;65            this.testSessionMessageLogger = TestSessionMessageLogger.Instance;66            this.testSessionMessageLogger.TestRunMessage += this.TestRunMessageHandler;67        }68        /// <summary>69        /// Property exposing the Instance70        /// </summary>71        public static IDesignModeClient Instance { get; private set; }72        /// <summary>73        /// Initializes DesignMode74        /// </summary>75        public static void Initialize()76        {77            Instance = new DesignModeClient();78        }79        /// <summary>80        /// Creates a client and waits for server to accept connection asynchronously81        /// </summary>82        /// <param name="port">83        /// Port number to connect84        /// </param>85        /// <param name="testRequestManager">86        /// The test Request Manager.87        /// </param>88        public void ConnectToClientAndProcessRequests(int port, ITestRequestManager testRequestManager)89        {90            EqtTrace.Info("Trying to connect to server on port : {0}", port);91            this.communicationManager.SetupClientAsync(new IPEndPoint(IPAddress.Loopback, port));92            var connectionTimeoutInSecs = EnvironmentHelper.GetConnectionTimeout();93            // Wait for the connection to the server and listen for requests.94            if (this.communicationManager.WaitForServerConnection(connectionTimeoutInSecs * 1000))95            {96                this.communicationManager.SendMessage(MessageType.SessionConnected);97                this.ProcessRequests(testRequestManager);98            }99            else100            {101                EqtTrace.Error("DesignModeClient : ConnectToClientAndProcessRequests : Client timed out while connecting to the server.");102                this.Dispose();103                throw new TimeoutException(104                    string.Format(105                        CultureInfo.CurrentUICulture,106                        CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage,107                        CoreUtilities.Constants.VstestConsoleProcessName,108                        "translation layer",109                        connectionTimeoutInSecs,110                        EnvironmentHelper.VstestConnectionTimeout)111                    );112            }113        }114        public void HandleParentProcessExit()115        {116            // Dispose off the communications to end the session117            // this should end the "ProcessRequests" loop with an exception118            this.Dispose();119            EqtTrace.Info("DesignModeClient: Parent process exited, Exiting myself..");120            this.platformEnvironment.Exit(1);121        }122        /// <summary>123        /// Process Requests from the IDE124        /// </summary>125        /// <param name="testRequestManager">126        /// The test Request Manager.127        /// </param>128        private void ProcessRequests(ITestRequestManager testRequestManager)129        {130            var isSessionEnd = false;131            do132            {133                try134                {135                    var message = this.communicationManager.ReceiveMessage();136                    if (EqtTrace.IsInfoEnabled)137                    {138                        EqtTrace.Info("DesignModeClient.ProcessRequests: Processing Message: {0}", message);139                    }140                    switch (message.MessageType)141                    {142                        case MessageType.VersionCheck:143                            {144                                var version = this.dataSerializer.DeserializePayload<int>(message);145                                this.protocolConfig.Version = Math.Min(version, this.protocolConfig.Version);146                                this.communicationManager.SendMessage(MessageType.VersionCheck, this.protocolConfig.Version);147                                break;148                            }149                        case MessageType.ExtensionsInitialize:150                            {151                                // Do not filter the Editor/IDE provided extensions by name152                                var extensionPaths = this.communicationManager.DeserializePayload<IEnumerable<string>>(message);153                                testRequestManager.InitializeExtensions(extensionPaths, skipExtensionFilters: true);154                                break;155                            }156                        case MessageType.StartTestSession:157                            {158                                var testSessionPayload = this.communicationManager.DeserializePayload<StartTestSessionPayload>(message);159                                this.StartTestSession(testSessionPayload, testRequestManager);160                                break;161                            }162                        case MessageType.StopTestSession:163                            {164                                var testSessionInfo = this.communicationManager.DeserializePayload<TestSessionInfo>(message);165                                this.StopTestSession(testSessionInfo);166                                break;167                            }168                        case MessageType.StartDiscovery:169                            {170                                var discoveryPayload = this.dataSerializer.DeserializePayload<DiscoveryRequestPayload>(message);171                                this.StartDiscovery(discoveryPayload, testRequestManager);172                                break;173                            }174                        case MessageType.GetTestRunnerProcessStartInfoForRunAll:175                        case MessageType.GetTestRunnerProcessStartInfoForRunSelected:176                            {177                                var testRunPayload =178                                    this.communicationManager.DeserializePayload<TestRunRequestPayload>(179                                        message);180                                this.StartTestRun(testRunPayload, testRequestManager, shouldLaunchTesthost: true);181                                break;182                            }183                        case MessageType.TestRunAllSourcesWithDefaultHost:184                        case MessageType.TestRunSelectedTestCasesDefaultHost:185                            {186                                var testRunPayload =187                                    this.communicationManager.DeserializePayload<TestRunRequestPayload>(188                                        message);189                                this.StartTestRun(testRunPayload, testRequestManager, shouldLaunchTesthost: false);190                                break;191                            }192                        case MessageType.TestRunAttachmentsProcessingStart:193                            {194                                var testRunAttachmentsProcessingPayload =195                                    this.communicationManager.DeserializePayload<TestRunAttachmentsProcessingPayload>(message);196                                this.StartTestRunAttachmentsProcessing(testRunAttachmentsProcessingPayload, testRequestManager);197                                break;198                            }199                        case MessageType.CancelDiscovery:200                            {201                                testRequestManager.CancelDiscovery();202                                break;203                            }204                        case MessageType.CancelTestRun:205                            {206                                testRequestManager.CancelTestRun();207                                break;208                            }209                        case MessageType.AbortTestRun:210                            {211                                testRequestManager.AbortTestRun();212                                break;213                            }214                        case MessageType.TestRunAttachmentsProcessingCancel:215                            {216                                testRequestManager.CancelTestRunAttachmentsProcessing();217                                break;218                            }219                        case MessageType.CustomTestHostLaunchCallback:220                            {221                                this.onCustomTestHostLaunchAckReceived?.Invoke(message);222                                break;223                            }224                        case MessageType.EditorAttachDebuggerCallback:225                            {226                                this.onAttachDebuggerAckRecieved?.Invoke(message);227                                break;228                            }229                        case MessageType.SessionEnd:230                            {231                                EqtTrace.Info("DesignModeClient: Session End message received from server. Closing the connection.");232                                isSessionEnd = true;233                                this.Dispose();234                                break;235                            }236                        default:237                            {238                                EqtTrace.Info("DesignModeClient: Invalid Message received: {0}", message);239                                break;240                            }241                    }242                }243                catch (Exception ex)244                {245                    EqtTrace.Error("DesignModeClient: Error processing request: {0}", ex);246                    isSessionEnd = true;247                    this.Dispose();248                }249            }250            while (!isSessionEnd);251        }252        /// <summary>253        /// Send a custom host launch message to IDE254        /// </summary>255        /// <param name="testProcessStartInfo">256        /// The test Process Start Info.257        /// </param>258        /// <param name="cancellationToken">259        /// The cancellation token.260        /// </param>261        /// <returns>262        /// The <see cref="int"/>.263        /// </returns>264        public int LaunchCustomHost(TestProcessStartInfo testProcessStartInfo, CancellationToken cancellationToken)265        {266            lock (this.lockObject)267            {268                var waitHandle = new AutoResetEvent(false);269                Message ackMessage = null;270                this.onCustomTestHostLaunchAckReceived = (ackRawMessage) =>271                {272                    ackMessage = ackRawMessage;273                    waitHandle.Set();274                };275                this.communicationManager.SendMessage(MessageType.CustomTestHostLaunch, testProcessStartInfo);276                // LifeCycle of the TP through DesignModeClient is maintained by the IDEs or user-facing-clients like LUTs, who call TestPlatform277                // TP is handing over the control of launch to these IDEs and so, TP has to wait indefinite278                // Even if TP has a timeout here, there is no way TP can abort or stop the thread/task that is hung in IDE or LUT279                // Even if TP can abort the API somehow, TP is essentially putting IDEs or Clients in inconsistent state without having info on280                // Since the IDEs own user-UI-experience here, TP will let the custom host launch as much time as IDEs define it for their users281                WaitHandle.WaitAny(new WaitHandle[] { waitHandle, cancellationToken.WaitHandle });282                cancellationToken.ThrowTestPlatformExceptionIfCancellationRequested();283                this.onCustomTestHostLaunchAckReceived = null;284                var ackPayload = this.dataSerializer.DeserializePayload<CustomHostLaunchAckPayload>(ackMessage);285                if (ackPayload.HostProcessId > 0)286                {287                    return ackPayload.HostProcessId;288                }289                else290                {291                    throw new TestPlatformException(ackPayload.ErrorMessage);292                }293            }294        }295        /// <inheritdoc/>296        public bool AttachDebuggerToProcess(int pid, CancellationToken cancellationToken)297        {298            // If an attach request is issued but there is no support for attaching on the other299            // side of the communication channel, we simply return and let the caller know the300            // request failed.301            if (this.protocolConfig.Version < ObjectModel.Constants.MinimumProtocolVersionWithDebugSupport)302            {303                return false;304            }305            lock (this.lockObject)306            {307                var waitHandle = new AutoResetEvent(false);308                Message ackMessage = null;309                this.onAttachDebuggerAckRecieved = (ackRawMessage) =>310                {311                    ackMessage = ackRawMessage;312                    waitHandle.Set();313                };314                this.communicationManager.SendMessage(MessageType.EditorAttachDebugger, pid);315                WaitHandle.WaitAny(new WaitHandle[] { waitHandle, cancellationToken.WaitHandle });316                cancellationToken.ThrowTestPlatformExceptionIfCancellationRequested();317                this.onAttachDebuggerAckRecieved = null;318                var ackPayload = this.dataSerializer.DeserializePayload<EditorAttachDebuggerAckPayload>(ackMessage);319                if (!ackPayload.Attached)320                {321                    EqtTrace.Warning(ackPayload.ErrorMessage);322                }323                return ackPayload.Attached;324            }325        }326        /// <summary>327        /// Send the raw messages to IDE328        /// </summary>329        /// <param name="rawMessage"></param>330        public void SendRawMessage(string rawMessage)331        {332            this.communicationManager.SendRawMessage(rawMessage);333        }334        /// <inheritdoc />335        public void SendTestMessage(TestMessageLevel level, string message)336        {337            var payload = new TestMessagePayload { MessageLevel = level, Message = message };338            this.communicationManager.SendMessage(MessageType.TestMessage, payload);339        }340        /// <summary>341        /// Sends the test session logger warning and error messages to IDE; 342        /// </summary>343        /// <param name="sender"></param>344        /// <param name="e"></param>345        public void TestRunMessageHandler(object sender, TestRunMessageEventArgs e)346        {347            // save into trace log and send the message to the IDE348            //349            // there is a mismatch between log levels that VS uses and that TP350            // uses. In VS you can choose Trace level which will enable Test platform351            // logs on Verbose level. Below we report Errors and warnings always to the 352            // IDE no matter what the level of VS logging is, but Info only when the Eqt trace 353            // info level is enabled (so only when VS enables Trace logging)354            switch (e.Level)355            {356                case TestMessageLevel.Error:357                    EqtTrace.Error(e.Message);358                    SendTestMessage(e.Level, e.Message);359                    break;...TestRunMessageHandler
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Microsoft.VisualStudio.TestPlatform.ObjectModel;7using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;8using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;9using Microsoft.VisualStudio.TestPlatform.Client.DesignMode;10{11    {12        static void Main(string[] args)13        {14            string testSource = "C:\\Users\\Public\\Documents\\Microsoft Visual Studio 2015\\Test\\TestAdapterTests\\TestAdapterTests\\bin\\Debug\\TestAdapterTests.dll";15            TestRunMessageHandler(testSource);16        }17        public static void TestRunMessageHandler(string testSource)18        {19            var designModeClient = new DesignModeClient();20            var testRunCriteria = new TestRunCriteria(new List<string>() { testSource }, 1, false, null, null, null);21            var testRunEventsHandler = new TestRunEventsHandler();22            designModeClient.RunTests(testRunCriteria, testRunEventsHandler);23            testRunEventsHandler.WaitForCompletion();24            Console.WriteLine("Press any key to exit");25            Console.ReadKey();26        }27    }28    {29        public void HandleLogMessage(TestMessageLevel level, string message)30        {31            Console.WriteLine(message);32        }33        public void HandleRawMessage(string rawMessage)34        {35            Console.WriteLine(rawMessage);36        }37        public void HandleTestRunComplete(38        {39            Console.WriteLine("Test run completed");40            Console.WriteLine("Test run complete args: " + testRunCompleteArgs.Error);41        }42        public void HandleTestRunStatsChange(TestRunChangedEventArgs testRunChangedArgs)43        {44            Console.WriteLine("Test run stats changed");45        }46        public void WaitForCompletion()47        {48            Console.WriteLine("Waiting for completion");49        }50    }51}TestRunMessageHandler
Using AI Code Generation
1using Microsoft.VisualStudio.TestPlatform.Client.DesignMode;2using Microsoft.VisualStudio.TestPlatform.ObjectModel;3using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;4using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;5using System;6using System.Collections.Generic;7using System.Linq;8using System.Text;9using System.Threading.Tasks;10{11    {12        static void Main(string[] args)13        {14            var designModeClient = new DesignModeClient();15            var testRunMessageHandler = new TestRunMessageHandler(designModeClient);16            {17                { "RunConfiguration.TargetFrameworkVersion", "Framework45" },18                { "RunConfiguration.TargetPlatform", "x86" }19            };20            var runConfiguration = new TestRunConfiguration(new Dictionary<string, string>(), new Dictionary<string, string>(), runSettings, null, null);21            var testRunCriteria = new TestRunCriteria(new List<string>() { "C:\\temp\\TestProject1.dll" }, 1, false, new TestPlatformOptions(), runConfiguration);22            var testHostLauncher = new DefaultTestHostLauncher();23            var testHostManager = new DefaultTestHostManager(testHostLauncher);24            designModeClient.InitializeCommunication();25            var testRunEventsHandler = new TestRunEventsHandler(designModeClient, testRunMessageHandler);26            designModeClient.StartTestRun(testRunCriteria, testHostManager, testRunEventsHandler);27            Console.ReadLine();28        }29    }30}31using Microsoft.VisualStudio.TestPlatform.Client.DesignMode;32using Microsoft.VisualStudio.TestPlatform.ObjectModel;33using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;34using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;35using System;36using System.Collections.Generic;37using System.Linq;38using System.Text;39using System.Threading.Tasks;40{41    {42        static void Main(string[] args)43        {44            var designModeClient = new DesignModeClient();45            var testRunMessageHandler = new TestRunMessageHandler(designModeClient);46            {47                { "RunConfiguration.TargetFrameworkVersion", "Framework45" },48                { "RunConfiguration.TargetPlatform", "x86" }49            };TestRunMessageHandler
Using AI Code Generation
1using Microsoft.VisualStudio.TestPlatform.Client.DesignMode;2using Microsoft.VisualStudio.TestPlatform.ObjectModel.Client;3using System;4using System.Collections.Generic;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8{9    {10        static void Main(string[] args)11        {12            string testSource = @"C:\Users\user\Documents\Visual Studio 2015\Projects\ClassLibrary1\ClassLibrary1\bin\Debug\ClassLibrary1.dll";13            string testAdapterPath = @"C:\Users\user\Documents\Visual Studio 2015\Projects\ClassLibrary1\ClassLibrary1\bin\Debug";14            string logFilePath = @"C:\Users\user\Documents\Visual Studio 2015\Projects\ClassLibrary1\ClassLibrary1\bin\Debug\log.txt";15            DesignModeClient designModeClient = new DesignModeClient();16            designModeClient.TestRunMessageHandler += (sender, e) =>17            {18                if (e != null && e.Message != null)19                {20                    Console.WriteLine(e.Message);21                }22            };23            designModeClient.TestRunComplete += (sender, e) =>24            {25                if (e != null)26                {27                    Console.WriteLine("Test Run Complete");28                }29            };30            designModeClient.RunTestsWithCustomTestHost(testSource, testAdapterPath, logFilePath);31            Console.ReadLine();32        }33    }34}35Microsoft (R) Test Execution Command Line Tool Version 14.0.23107.0TestRunMessageHandler
Using AI Code Generation
1var designModeClient = new DesignModeClient();2var designModeTestEventsHandler = new DesignModeTestEventsHandler();3designModeClient.TestRunMessageHandler += designModeTestEventsHandler.TestMessageHandler;4var testRunCriteria = new TestRunCriteria(new List<string> { "TestProject.dll" }, 1, false, new TestPlatformOptions(), new TestFrameworkOptions(new List<string> { "TestFramework" }));5await designModeClient.RunTestsWithSourcesAsync(testRunCriteria);6var designModeClient = new DesignModeClient();7var designModeTestEventsHandler = new DesignModeTestEventsHandler();8designModeClient.TestRunMessageHandler += designModeTestEventsHandler.TestMessageHandler;9var testRunCriteria = new TestRunCriteria(new List<string> { "TestProject.dll" }, 1, false, new TestPlatformOptions(), new TestFrameworkOptions(new List<string> { "TestFramework" }));10await designModeClient.RunTestsWithSourcesAsync(testRunCriteria);11var designModeClient = new DesignModeClient();12var designModeTestEventsHandler = new DesignModeTestEventsHandler();13designModeClient.TestRunMessageHandler += designModeTestEventsHandler.TestMessageHandler;14var testRunCriteria = new TestRunCriteria(new List<string> { "TestProject.dll" }, 1, false, new TestPlatformOptions(), new TestFrameworkOptions(new List<string> { "TestFramework" }));15await designModeClient.RunTestsWithSourcesAsync(testRunCriteria);16var designModeClient = new DesignModeClient();17var designModeTestEventsHandler = new DesignModeTestEventsHandler();18designModeClient.TestRunMessageHandler += designModeTestEventsHandler.TestMessageHandler;19var testRunCriteria = new TestRunCriteria(new List<string> { "TestProject.dll" }, 1, false, new TestPlatformOptions(), new TestFrameworkOptions(new List<string> { "TestFramework" }));Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
