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

问题描述 投票:0回答:1

我使用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] 

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

java swing assertj
1个回答
0
投票

解决问题的最佳和最简单的方法是,如果您可以为按钮指定不同的名称。

请记住:组件的name与它显示的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,它只返回与给定文本匹配的nth按钮。

请注意:

  • 如果所有其他方法都失败,这是一个绝望的措施
  • 这将导致脆弱的测试
  • 除非绝对没有别的办法,否则你不想这样做!

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

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;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.