0

I use AssertJ to test my swing application. When I try to use this code

frame.button(JButtonMatcher.withText("text").andShowing()).click();` 

I get this error:

Found more than one component using matcher org.assertj.swing.core.matcher.JButtonMatcher[
    name=<Any>, text='text', requireShowing=true] 

Because I have three identical components in one form and I can't change names or titles of this one. Any advice?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Vadym
  • 163
  • 1
  • 4
  • 19
  • *"Any advice?"* Don't build confusing GUIs. How is the user supposed to determine which of three identical buttons to activate? – Andrew Thompson Jun 06 '18 at 01:48
  • In the panel we have 3 another panels which contains any elements, and one of this element is this button which has the same names – Vadym Jun 06 '18 at 16:38
  • Way to vague this up! I am no closer to determining the answer to my question than I was before. – Andrew Thompson Jun 06 '18 at 23:36
  • So, I'm agree with You, but I have code, which I may test, but don't edit. The best way is change method of initialize that buttons. – Vadym Jun 07 '18 at 13:19

1 Answers1

0

The best and easiest solution to your problem would be if you could give the buttons distinct names.

Remember: the name of a component is distinct from the text it displays! Your buttons could all be showing "text" to the users, but still have names like "button1", "button2", "button3".

In this case you could write

frame.button(JButtonMatcher.withName("button1").withText("text").andShowing()).click();

The next possibility would be to give the panels containing the buttons distinct names, for example "panel1", "panel2", "panel3".

If you can implement this you could write

frame.panel("panel1").button(JButtonMatcher.withText("text").andShowing()).click();

The last and worst possibility would be to write your own GenericTypeMatcher / NamedComponentMatcherTemplate that returns only the nth button matching the given text.

PLEASE BEWARE:

  • this is a desparate measure if all other approaches fail
  • This will lead to fragile tests
  • You don't want to do this unless there is absolute no other way!

With these warnings in place, this is code:

public class MyJButtonMatcher extends NamedComponentMatcherTemplate<JButton> {

    private String text;
    private int index;

    public MyJButtonMatcher(String text, int index) {
        super(JButton.class);
        this.text = text;
        this.index = index;
        requireShowing(true);
    }

    @Override
    protected boolean isMatching(JButton button) {
        if (isNameMatching(button.getName()) && arePropertyValuesMatching(text, button.getText())) {
            return index-- == 0;
        } else {
            return false;
        }
    }
}
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34