Extensibility- Extend Existing Elements- Extension Methods

Learn how to extend BELLATRIX desktop elements using extension methods.

Example

using Bellatrix.Desktop.GettingStarted.Advanced.Elements.Extension.Methods;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Bellatrix.Desktop.GettingStarted
{
    [TestFixture]
    public class ExtendExistingElementWithExtensionMethodsTests : DesktopTest
    {
        [Test]
        public void MessageChanged_When_ButtonClicked_Wpf()
        {
            var button = App.Components.CreateByName<Button>("E Button");

            // 2. Use the custom added submit button behaviour through 'Enter' key.
            button.SubmitButtonWithEnter();

            var label = App.Components.CreateByName<Button>("ebuttonClicked");
            Assert.AreEqual("ebuttonClicked", label.InnerText);
        }
    }
}

Explanations

namespace Bellatrix.Desktop.GettingStarted.Advanced.Elements.Extension.Methods
{
    public static class ButtonExtensions
    {
        public static void SubmitButtonWithEnter(this Button button)
        {
            var action = new Actions(button.WrappedDriver);
            action.MoveToElement(button.WrappedElement).SendKeys(Keys.Enter).Perform();
        }
    }
}

One way to extend an existing element is to create an extension method for the additional action.

  1. Place it in a static class like this one.
  2. Create a static method for the action.
  3. Pass the extended element as a parameter with the keyword ‘this’.
  4. Access the native element through the WrappedElement property and the driver via WrappedDriver.

Later to use the method in your tests, add a using statement containing this class’s namespace.

using Bellatrix.Desktop.GettingStarted.Advanced.Elements.Extension.Methods;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Bellatrix.Desktop.GettingStarted

To use the additional method you created, add a using statement to the extension methods’ namespace.

button.SubmitButtonWithEnter();

Use the custom added submit button behaviour through ‘Enter’ key.