使用 AssertJ 选择三个相同的摆动组件之一

Choose one of three identical swing components using AssertJ

我使用 AssertJ 来测试我的 swing 应用程序。当我尝试使用此代码时

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

我收到此错误:

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

因为我在一个表格中有三个相同的组件,我不能更改这个的名称或标题。有什么建议吗?

解决您的问题的最好和最简单的方法是为按钮指定不同的名称。

记住:组件的 name 与它显示的 text 是不同的!您的按钮可能都向用户显示 "text",但名称仍然像 "button1"、"button2"、"button3".

在这种情况下你可以写

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

下一种可能性是为包含按钮的面板指定不同的名称,例如 "panel1"、"panel2"、"panel3".

如果你能实现这个你可以写

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

最后也是最糟糕的可能性是编写您自己的 GenericTypeMatcher / NamedComponentMatcherTemplate,returns 只有第 n 个按钮匹配给定的文本。

请注意

  • 如果所有其他方法都失败了,这是一个孤注一掷的措施
  • 这将导致脆弱的测试
  • 除非别无他法,否则你不想这样做!

有了这些警告,这是代码:

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;
        }
    }
}