UI Automation for Dynamics 365 CE – EasyRepro (Part 2)

In this post I will cover how to get started using EasyRepro framework for Dynamics 365 CE. If you are new to UI Automation, take a look at my previous Introduction post.

Note the framework consists of a single solution that contains a sample project. If you just want to take a look and get an idea, you can download the source code from the GitHub project and take a look at the sample test project.

Unless you want to contribute to the framework or debug the framework code you are more likely to just consume the framework libraries and focus on building your tests. This is the scenario I will cover in this post.

Scenario

Login to CRM
Navigate to Sales/Contacts/Active Contacts
Create a new Contact
Save

Create a Unit Test project

You can use any unit testing framework you like. I will use MSTest. For this just add a new unit testing project to your solution as per below. Note you need to select .NET 4.7 as the Nuget packages doesn’t seem to install correctly with lower versions.

UIAutomationProject

Add the required NuGet packages

Add the EasyRepro library from the Nuget Gallery . Not sure if this published by MS. As an alternative you can compile the sample project from GitHub and add the Microsoft.Dynamics365.UIAutomation.Api and Microsoft.Dynamics365.UIAutomation.Browser DLLs as a reference).

EasyReproNuget

Below are all the package syou need along with the versions.

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Dynamics365.UIAutomation.Api" version="9.0.0" targetFramework="net47" />
  <package id="MSTest.TestAdapter" version="1.1.18" targetFramework="net461" />
  <package id="MSTest.TestFramework" version="1.1.18" targetFramework="net461" />
  <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net47" />
  <package id="Selenium.Chrome.WebDriver" version="2.31" targetFramework="net47" />
  <package id="Selenium.Support" version="3.5.1" targetFramework="net47" />
  <package id="Selenium.WebDriver" version="3.5.1" targetFramework="net47" />
  <package id="System.Diagnostics.DiagnosticSource" version="4.4.1" targetFramework="net47" />
</packages><span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>

Add a Test

As a standard unit test to your project.
CreateContactTest

First you will need your CRM URL, Username and Password. Below I am retrieving these from Environment variables as I didn’t want to check-in credentials to into source control. You can use configuration files. I strongly recommend that credentials are encrypted and securely stored.

        private readonly SecureString _username = Environment.GetEnvironmentVariable("CRMUser", EnvironmentVariableTarget.User).ToSecureString();
        private readonly SecureString _password = Environment.GetEnvironmentVariable("CRMPassword", EnvironmentVariableTarget.User).ToSecureString();
        private readonly Uri _xrmUri = new Uri(Environment.GetEnvironmentVariable("CRMUrl", EnvironmentVariableTarget.User));

Next you will need to define your browser requirements. In this instance I will use Chrome in Private (Incognito mode).

        private readonly BrowserOptions _options = new BrowserOptions
        {
            BrowserType = BrowserType.Chrome,
            PrivateMode = true,
            FireEvents = true
        };

The first step is normally to open a new browser instance and login to CRM. As you can see the below API make this very simple to achieve.

            using (var xrmBrowser = new XrmBrowser(_options))
            {
                xrmBrowser.LoginPage.Login(_xrmUri, _username, _password);
                xrmBrowser.GuidedHelp.CloseGuidedHelp();

Once CRM is open. You can interact with CRM page using the XrmBrowser object. As you can see below, there are different components for Navigation, Grids and CommandBar. Note you will need to add some think time between different calls to allow the browser to do its work.


                xrmBrowser.Navigation.OpenSubArea("Sales", "Contacts");

                xrmBrowser.ThinkTime(2000);
                xrmBrowser.Grid.SwitchView("Active Contacts");

                xrmBrowser.ThinkTime(1000);
                xrmBrowser.CommandBar.ClickCommand("New");

                xrmBrowser.ThinkTime(5000);

Once you are on the new contact page, you can interact with the CRM entity form through the Entity component. This allows you to set values on the form. This can be simple texts fields or even composite controls and lookups.

                var fields = new List<Field>
                {
                    new Field() {Id = "firstname", Value = "Wael"},
                    new Field() {Id = "lastname", Value = "Test"}
                };
                xrmBrowser.Entity.SetValue(new CompositeControl() { Id = "fullname", Fields = fields });
                xrmBrowser.Entity.SetValue("emailaddress1", "test@contoso.com");
                xrmBrowser.Entity.SetValue("mobilephone", "555-555-5555");
                xrmBrowser.Entity.SetValue("birthdate", DateTime.Parse("11/1/1980"));
                xrmBrowser.Entity.SetValue(new OptionSet { Name = "preferredcontactmethodcode", Value = "Email" });

Now you can save the form.

                xrmBrowser.CommandBar.ClickCommand("Save");
                xrmBrowser.ThinkTime(5000);

Finally I will take a screen shot. You can take these at any point in time during the test or if the test fails. This can be used as test evidence, troubleshooting failed tests or for spot checks.

                string screenShot = string.Format("{0}\\CreateNewContact.jpeg", TestContext.TestResultsDirectory);
                xrmBrowser.TakeWindowScreenShot(screenShot, ScreenshotImageFormat.Jpeg);
                TestContext.AddResultFile(screenShot);

Run the Test

If you run the test now the browser should navigate to CRM and perform the actions described in the scenario. You will normally add some verification at the end of the test to ensure the expected outcome was achieved and fail the test otherwise.

CreateContactTestResults
CreateContactScreenShot

You can find this code including any future updates on GitHub

As you can see it very easy to setup an automated UI test using EasyRepro. In the following posts I will cover more advanced topics on UI Automation.

12 thoughts on “UI Automation for Dynamics 365 CE – EasyRepro (Part 2)

  1. Hey…..I’m getting the following message while executing the code which you’ve explained above….

    Message: Unable to create instance of class UnitTestProject1.UnitTest1. Error: System.NullReferenceException: Object reference not set to an instance of an object..

  2. When I run the API 8.2 version in VS 2015 with .net framework 4.6/4.6.1, it always complains “Xrm not defined”. Have you met this issue before? Should I upgrade the .net framework to 4.7?

  3. Hi….
    I’m getting the following message while running this code…

    Message: Test method Xrm.CI.Framework.Sample.UIAutomation.CreateContactTest.CreateNewContact threw exception:
    System.TypeLoadException: Could not load type ‘OpenQA.Selenium.Support.UI.WebDriverWait’ from assembly ‘WebDriver.Support, Version=3.9.1.0, Culture=neutral, PublicKeyToken=null’.

    StackTrace:

    SeleniumExtensions.WaitUntilAvailable(IWebDriver driver, By by, TimeSpan timeout, Action’1 successCallback, Action’1 failureCallback)

    SeleniumExtensions.WaitUntilAvailable(IWebDriver driver, By by, String exceptionMessage)
    LoginPage.Login(IWebDriver driver, Uri uri, SecureString username, SecureString password, Action’1 redirectAction)
    DelegateBrowserCommand’5.ExecuteCommand(WebDriver driver, Object[] params)
    BrowserCommand’1.Execute[T1,T2,T3,T4,T5,T6,T7,T8,T9](IWebDriver driver, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5, T6 p6, T7 p7, T8 p8, T9 p9)
    BrowserCommand’1.Execute[T1,T2,T3,T4](IWebDriver driver, T1 p1, T2 p2, T3 p3, T4 p4 )
    BrowserPage.Execute[TResult, T1, T2, T3, T4](BroswerCommandOptions options, Func’6 delegate, T1 p1, T2 p2, T3 p3, T4 p4)
    LoginPage.Login(Uri, uri, SecureString username, SecureString password, Action’1 redirectAction)
    CreateContactTest.CreateNewContact()

  4. I’ve another issue to report…..while saving the record on quick form it is not saving in the grid….

    This is the code I’m using

    xrmBrowser.Navigation.QuickCreate(“Patient Problem”);
    xrmBrowser.QuickCreate.SetValue(“diagnosisconceptid”, patientDiagnosis);
    xrmBrowser.QuickCreate.SetValue(“onsetdate”, patientAllergyOnSetDate);
    xrmBrowser.QuickCreate.SetValue(“comments”, patientAllergyComments);
    xrmBrowser.ThinkTime(10000);
    xrmBrowser.QuickCreate.Save();

    NOTE: I can see the values on the quick form during automation but it never shows in the grid after the save…wondering, am i missing anything here????

    Thanks in Advance..

Leave a reply to waelhamze Cancel reply