Click here to Skip to main content
13,898,580 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

17.6K views
13 bookmarked
Posted 4 Jan 2016
Licenced CPOL

Strategy Pattern-C#

, 24 Feb 2016
Rate this:
Please Sign up or sign in to vote.
This is an alternative for "Strategy Pattern-C#"

Introduction

In my previous articles from the series “Design Patterns in Automation Testing“, I explained in detail how to make your test automation framework better through the implementation of Page ObjectsFacades, and Singletons. When we have to write tests for more complex use case scenarios, it gets usually harder and harder to follow the Open Close Principle, one of the primary principles part of SOLID. In this part of the series, I am going to use the Strategy Design Pattern to create extendable validators for an E-Commerce module.

Definition

In computer programming, the strategy pattern (also known as the policy pattern) is a software design pattern that enables an algorithm‘s behavior to be selected at runtime.

  • Defines a family of algorithms
  • Encapsulates each algorithm
  • Makes the algorithms interchangeable within that family
  • The code is easier to maintain as modifying or understanding strategy does not require you to understand the whole primary object

UML Class Diagram

Participants

The classes and objects participating in this pattern are:

  • IStrategy (IOrderValidationStrategy) – Defines an interface common to all algorithms. The context class calls the interface to perform the algorithm, identified by the concrete strategy.
  • ConcreteStrategy (SalesTaxOrderValidationStrategy)- Implements the algorithm using the strategy interface.
  • Context (PurchaseContext) – Holds a dependency to IStrategy. Wraps the calls to the concrete strategies, may provide an interface to access its data.

Strategy Design Pattern C# Code

Test’s Test Case

The primary goal of the below tests is going to be to purchase different items from Amazon. Also, the prices on the last step of the buying process should be validated- taxes, shipping costs, gift wrapping expenses, etc.

  1. Navigate to Item’s Page

  2. Click Proceed to Checkout
  3. Login with an existing Client

  4. Fill Shipping Info

  5. Choose a shipping speed
  6. Select a payment method

  7. Validate the Order Summary

The primary goal of the design of the related test classes is to enable a decoupled and extendable validation of the different prices on the last page of the purchasing process.

The following class structure is going to be used.

As you can see, the design of the tests uses heavily Page Object Pattern. There is nothing unusual in the different pages, so I’m not going to paste the code of every single page here because it is not relevant to the articles’ theme. Probably, the most interesting logic is located in the ShippingAddressPage.

public class ShippingAddressPage : BasePageSingleton<ShippingAddressPage, ShippingAddressPageMap>
{
    public void ClickContinueButton()
    {
        this.Map.ContinueButton.Click();
    }

    public void FillShippingInfo(ClientPurchaseInfo clientInfo)
    {
        this.Map.CountryDropDown.SelectByText(clientInfo.Country);
        this.Map.FullNameInput.SendKeys(clientInfo.FullName);
        this.Map.Address1Input.SendKeys(clientInfo.Address1);
        this.Map.CityInput.SendKeys(clientInfo.City);
        this.Map.ZipInput.SendKeys(clientInfo.Zip);
        this.Map.PhoneInput.SendKeys(clientInfo.Phone);
        this.Map.ShipToThisAddress.Click();
    }
}

The ClientPurchaseInfo class holds the data about the client’s purchase, most of the data is populated through string properties.

public class ClientPurchaseInfo
{
    public string FullName { get; set; }

    public string Country { get; set; }

    public string Address1 { get; set; }

    public string City { get; set; }

    public string Phone { get; set; }

    public string Zip { get; set; }

    public string Email { get; set; }

    public string State { get; set; }

    public string DeliveryType { get; set; }

    public GiftWrappingStyles GiftWrapping { get; set; }
}

Implementation without Strategy Design Pattern

The use cases can be automated easily via the usage of Facade Design Pattern.

public class PurchaseFacade
{
    public void PurchaseItemSalesTax(string itemUrl, string itemPrice, 
    string taxAmount, ClientLoginInfo clientLoginInfo, ClientPurchaseInfo clientPurchaseInfo)
    {
        PurchaseItemInternal(itemUrl, clientLoginInfo, clientPurchaseInfo);
        PlaceOrderPage.Instance.Validate().EstimatedTaxPrice(taxAmount);
    }

    public void PurchaseItemGiftWrapping(string itemUrl, string itemPrice, 
    string giftWrapTax, ClientLoginInfo clientLoginInfo, ClientPurchaseInfo clientPurchaseInfo)
    {
        PurchaseItemInternal(itemUrl, clientLoginInfo, clientPurchaseInfo);
        PlaceOrderPage.Instance.Validate().GiftWrapPrice(giftWrapTax);
    }

    public void PurchaseItemShippingTax(string itemUrl, string itemPrice, 
    string shippingTax, ClientLoginInfo clientLoginInfo, ClientPurchaseInfo clientPurchaseInfo)
    {
        PurchaseItemInternal(itemUrl, clientLoginInfo, clientPurchaseInfo);
        PlaceOrderPage.Instance.Validate().ShippingTaxPrice(shippingTax);
    }

    private void PurchaseItemInternal(string itemUrl, 
    ClientLoginInfo clientLoginInfo, ClientPurchaseInfo clientPurchaseInfo)
    {
        ItemPage.Instance.Navigate(itemUrl);
        ItemPage.Instance.ClickBuyNowButton();
        PreviewShoppingCartPage.Instance.ClickProceedToCheckoutButton();
        SignInPage.Instance.Login(clientLoginInfo.Email, clientLoginInfo.Password);
        ShippingAddressPage.Instance.FillShippingInfo(clientPurchaseInfo);
        ShippingAddressPage.Instance.ClickContinueButton();
        ShippingPaymentPage.Instance.ClickBottomContinueButton();
        ShippingPaymentPage.Instance.ClickTopContinueButton();
    }
}

The main drawback of such solution is the number of different methods for the different tax verification cases. If there is a need to introduce a new tax validation, a new method should be added that is going to break the Open Close Principle.

Strategy Design Pattern Implementation

There are hundreds of test cases that you can automate in this sample e-commerce module. Some of the most important are related to the correctness of the prices on the last page of the purchasing process. So the primary goal of the validations in the tests is going to be to test if the correct prices are displayed. There are a couple of types of taxes- Sales (US/Canada), VAT (EU Union Countries), Gift Wrapping, Shipping, etc. The page objects can be combined in the PurchaseContext class to perform a new purchase, the strategy design pattern can be applied to pass the specific validation strategy.

The main method of the validation strategy can be defined by the following interface.

public interface IOrderValidationStrategy
{
    void ValidateOrderSummary(string itemPrice, ClientPurchaseInfo clientPurchaseInfo);
}

The PurchaseContext class is almost identical to the already discussed facade classes; the only difference is that it holds a dependency to the IOrderValidationStrategy.

The concrete validation strategy is passed to its constructor.

public class PurchaseContext
{
    private readonly IOrderValidationStrategy orderValidationStrategy;

    public PurchaseContext(IOrderValidationStrategy orderValidationStrategy)
    {
        this.orderValidationStrategy = orderValidationStrategy;
    }

    public void PurchaseItem(string itemUrl, string itemPrice, 
    ClientLoginInfo clientLoginInfo, ClientPurchaseInfo clientPurchaseInfo)
    {
        ItemPage.Instance.Navigate(itemUrl);
        ItemPage.Instance.ClickBuyNowButton();
        PreviewShoppingCartPage.Instance.ClickProceedToCheckoutButton();
        SignInPage.Instance.Login(clientLoginInfo.Email, clientLoginInfo.Password);
        ShippingAddressPage.Instance.FillShippingInfo(clientPurchaseInfo);
        ShippingAddressPage.Instance.ClickContinueButton();
        ShippingPaymentPage.Instance.ClickBottomContinueButton();
        ShippingPaymentPage.Instance.ClickTopContinueButton();
        this.orderValidationStrategy.ValidateOrderSummary(itemPrice, clientPurchaseInfo);
    }
}

In most cases, I believe that the best approach to validating taxes and similar money amounts is to call the real production web services that are used to power the actual e-commerce module. They should be already entirely tested via unit and integration tests, and their output should be guaranteed.

The primary goal of the E2E tests is to ensure that the correct prices are visualized on the page rather than to check the real calculation logic. So in my concrete implementation of the SalesTaxOrderValidationStrategy, I have created a dummy sample implementation. In actual tests instead of calculating the taxes manually, we should call the production web service. If the module doesn’t use web services, you can always create your test web-service and call the production code in wrapper methods. I had already done that for an old legacy module that I had to validate automatically.

public class SalesTaxOrderValidationStrategy : IOrderValidationStrategy
{
    public SalesTaxOrderValidationStrategy()
    {
        this.SalesTaxCalculationService = new SalesTaxCalculationService();
    }

    public SalesTaxCalculationService SalesTaxCalculationService { get; set; }

    public void ValidateOrderSummary(string itemsPrice, ClientPurchaseInfo clientPurchaseInfo)
    {
        States currentState = (States)Enum.Parse(typeof(States), clientPurchaseInfo.State);
        decimal currentItemPrice = decimal.Parse(itemsPrice);
        decimal salesTax = this.SalesTaxCalculationService.Calculate
				(currentItemPrice, currentState, clientPurchaseInfo.Zip);

        PlaceOrderPage.Instance.Validate().EstimatedTaxPrice(salesTax.ToString());
    }
}

I have implemented a similar logic for the VAT Tax Validation Strategy.

public class VatTaxOrderValidationStrategy : IOrderValidationStrategy
{
    public VatTaxOrderValidationStrategy()
    {
        this.VatTaxCalculationService = new VatTaxCalculationService();
    }

    public VatTaxCalculationService VatTaxCalculationService { get; set; }

    public void ValidateOrderSummary(string itemsPrice, ClientPurchaseInfo clientPurchaseInfo)
    {
        Countries currentCountry = (Countries)Enum.Parse(typeof(Countries), clientPurchaseInfo.Country);
        decimal currentItemPrice = decimal.Parse(itemsPrice);
        decimal vatTax = this.VatTaxCalculationService.Calculate(currentItemPrice, currentCountry);

        PlaceOrderPage.Instance.Validate().EstimatedTaxPrice(vatTax.ToString());
    }
}

One of the essential benefits of the usage of the Strategy Design Pattern is that if a new tax is introduced in the application, you don’t have to modify your existing pages or the PurchaseContext. You will need only to create a new concrete strategy.

For example, if Amazon announces that from tomorrow a supermodel can deliver you the desired items directly to your door, only for 100 bucks. You can handle the new tax validation by creating a new SuperModelOrderValidationStrategy. Imagine Brad Pitt bringing a refrigerator on his back, I will pay to see this.

 

Tests Using Strategy Design Pattern

[TestClass]
public class AmazonPurchase_PurchaseStrategy_Tests
{       
    [TestInitialize]
    public void SetupTest()
    {
        Driver.StartBrowser();
    }

    [TestCleanup]
    public void TeardownTest()
    {
        Driver.StopBrowser();
    }

    [TestMethod]
    public void Purchase_SeleniumTestingToolsCookbook()
    {
        string itemUrl = "/Selenium-Testing-Cookbook-Gundecha-Unmesh/dp/1849515743";
        string itemPrice = "40.49";
        ClientPurchaseInfo clientPurchaseInfo = new ClientPurchaseInfo()
        {
            FullName = "John Smith",
            Country = "United States",
            Address1 = "950 Avenue of the Americas",
            State = "New York",
            City = "New York City",
            Zip = "10001-2121",
            Phone = "00164644885569",
            GiftWrapping = Enums.GiftWrappingStyles.None
        };
        ClientLoginInfo clientLoginInfo = new ClientLoginInfo()
        {
            Email = "g3984159@trbvm.com",
            Password = "ASDFG_12345"
        };

        new PurchaseContext(new SalesTaxOrderValidationStrategy()).PurchaseItem
        	(itemUrl, itemPrice, clientLoginInfo, clientPurchaseInfo);
    }
}

The use of the Strategy Design Pattern to create automated tests is easy. The only thing that you have to do is to pass the desired algorithm to the newly created PurchaseContext.

So Far in the "Design Patterns in Automated Testing" Series

  1. Page Object Pattern
  2. Advanced Page Object Pattern
  3. Facade Design Pattern
  4. Singleton Design Pattern
  5. Fluent Page Object Pattern
  6. IoC Container and Page Objects
  7. Strategy Design Pattern
  8. Advanced Strategy Design Pattern
  9. Observer Design Pattern
  10. Observer Design Pattern via Events and Delegates
  11. Observer Design Pattern via IObservable and IObserver
  12. Decorator Design Pattern- Mixing Strategies
  13. Page Objects That Make Code More Maintainable
  14. Improved Facade Design Pattern in Automation Testing v.2.0
  15. Rules Design Pattern
  16. Specification Design Pattern
  17. Advanced Specification Design Pattern

Source Code

If you like the article, please hit these share buttons. Thank you!

References

All images are purchased from DepositPhotos.com and cannot be downloaded and used for free. License Agreement

The post- Strategy Design Pattern in Automation Testing appeared first on Automate The Planet.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Anton Angelov
CEO Automate The Planet
Bulgaria Bulgaria
Anton Angelov is an IT Consultant and Quality Assurance Architect at Innovative Lab. He is passionate about automation testing and designing test harness and tools, having the best industry development practices in mind. In addition, he is an active blogger and the founder of Automate The Planet. He strives to make the site one of the leading authorities in Automation Testing by presenting compelling articles, inspiring ardent discussions amongst the community. He is also one of the most-rated-answer authors of questions about Test Automation Frameworks (WebDriver) on Stack Overflow.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Forhad Reza15-Nov-16 8:34
memberForhad Reza15-Nov-16 8:34 
Question[My vote of 2] Not the real power of strategy pattern Pin
Rahul Dhammy4-Jan-16 9:03
professionalRahul Dhammy4-Jan-16 9:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190306.1 | Last Updated 25 Feb 2016
Article Copyright 2016 by Anton Angelov
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid