1

I want to replace if else statements:

    if (userSalutation.equalsIgnoreCase("mr")) {
        screenPage.selectMr();
    } else {
        screenPage.selectMs();
    }

selectMr() performs just click on this buttons.

With Command pattern implementation.
Using enums implementation for this aim.

I have to use if for web page elements (buttons):

enter image description here

Code snippet:

public class ScanScreenPageStep1 extends PageObject {
    public ScanScreenPageStep1() {
        PageFactory.initElements(new EasyWebFieldDecorator(getDriver()), this);
    }
    @FindBy(id = "salutation")
    protected Button mr;

    @FindBy(id = "salutation2")
    protected Button ms;

Here is enum looking:

public enum PersonSalutations {
        MR("mr") {
            @Override
            public Button getButton() {
                return mr;
            }
        },    
        MS("ms") {
            @Override
            public Button getButton() {
                return ms;
            }
        };
        private String salutation;

        PersonSalutations(String salutation) {
            this.salutation = salutation;
        }

        public static final Map<String, Button> stringToButton = new HashMap<>();            
        static {
            for (PersonSalutations salut : values()) {
                stringToButton.put(salut.toString(), salut.getButton());
            }
        }

        public String getSalutation() {
            return salutation;
        }

        public abstract Button getButton();

        public static Button fromString(String stringSalutation) {
            return stringToButton.get(stringSalutation);
        }    

        @Override
        public String toString() {
            return salutation.toUpperCase();
        }
    }

For adding buttons element to stringToButton I have to make my button element static:

@FindBy(id = "salutation")
protected static Button mr;

@FindBy(id = "salutation2")
protected static Button ms;

How to avoid making elements static at this case?

Or some other circumstances at this case.

catch23
  • 17,519
  • 42
  • 144
  • 217

1 Answers1

0

Your enum defines the conceptual button, while protected Button mr defines an instance of the button. Except for singleton pattern, that's like asking a Class for an instance of the class. Your code has more than one instance of Button, so singleton doesn't apply here.

You should move getButton to ScanScreenPageStep1 as follows:

public Button getButton(PersonSalutations s) {
    if (s == PersonSalutations.MR)
        return this.mr;
    if (s == PersonSalutations.MS)
        return this.ms;
    throw new IllegalArgumentException("Invalid: " + s);
}

As an alternative, add ScanScreenPageStep1 as a parameter to getButton, so the enum known which "step 1" instance to get the button of.

Andreas
  • 154,647
  • 11
  • 152
  • 247