使用 TestNG-Abbot,可以通过这三个方便的 fixture 类型执行上面所属的三个步骤:TextComponentFixture 用于 JTextField;ButtonFixture 用于 Find Word 按钮;LabelFixture 用来验证 JLabel 中特定的文本。
清单 2 显示了用于验证 图 3 中演示的内容是否可以正常工作的代码:
@Test public void assertDefinitionPresent() { TextComponentFixture text1 = new TextComponentFixture(this.fixture, "wordValue"); text1.enterText("pugnacious"); ButtonFixture bfix = new ButtonFixture(this.fixture, "findWord"); bfix.click(); LabelFixture fix = new LabelFixture(this.fixture, "definition"); fix.shouldHaveThisText("Combative in nature; belligerent."); }
注意 fixture 对象通过一个逻辑名称和特定的 GUI 组件连接在一起。例如,在 Word Finder GUI 中,通过编程将 JButton 对象与 “findWord” 名称联系起来。请注意在定义按钮时,我是如何通过调用组件的 setName() 方法做到这点的,如清单 3 所示:
清单 3. 定义 Find Word 按钮
findWordButton = new JButton(); findWordButton.setBounds(new Rectangle(71, 113, 105, 29)); findWordButton.setText("Find Word"); findWordButton.setName("findWord");
同样要注意,在 清单 2 中,我是如何通过将 “findWord” 名称传递给 TestNG-Abbot 的 ButtonFixture 对象而获得对按钮的引用。“单击” 按钮(调用 click 方法)然后使用 TestNG-Abbot 的 LabelFixture 对象插入单词的释义,多么酷!不过不要就此满足。
当然,如果我非常希望验证我的 Word Finder GUI,我必须确保在用户执行意外操作时 —— 程序能够正常工作,比如在输入单词之前按下 Find Word 按钮,或者情况更糟,比如他们输入了一个无效的单词。举例来说,如果用户没有向文本字段输入内容,GUI 应该显示特定的信息,如清单 4 所示:
当然,使用 TestNG-Abbot 测试这种情况非常简单,不是吗?我所做的仅仅是将空值传送到 TextComponentFixture 中,按下按钮(通过对 ButtonFixture 使用 click 方法)并插入 “Please enter a valid word” 响应!
清单 4. 测试一个极端例子:如果有人没有输入单词就按下了按钮该怎么办?
@Test public void assertNoWordPresentInvalidText() { TextComponentFixture text1 = new TextComponentFixture(this.fixture, "wordValue"); text1.enterText(""); ButtonFixture bfix = new ButtonFixture(this.fixture, "findWord"); bfix.click(); LabelFixture fix = new LabelFixture(this.fixture, "definition"); fix.shouldHaveThisText("Please enter a valid word"); }
如清单 4 所示,一旦理解了获得所需 GUI 组件的引用时,事情并不是很困难。最后一步是检验其他 糟糕的极端例子 —— 输入了无效的单词。这个过程与 清单 1 和 清单 3 非常相似:仅仅是将所需的 String 传递到 TextComponentFixture 对象,单击,然后插入特定的文本。如清单 5 所示:
@Test public void assertNoWordPresentInvalidText() { TextComponentFixture text1 = new TextComponentFixture(this.fixture, "wordValue"); text1.enterText("Ha77"); ButtonFixture bfix = new ButtonFixture(this.fixture, "findWord"); bfix.click(); LabelFixture fix = new LabelFixture(this.fixture, "definition"); fix.shouldHaveThisText("Word doesn't exist in dictionary"); }
清单 5 很好地验证了图 5 演示的功能,难道您不这样认为吗?
图 5. 输入了无效单词

TestNG-Abbot 可能是测试工具中的新生儿,但它从其前辈那里继承了一些非常有用的特性。本文向您展示了如何使用 TestNG-Abbot 通过编程的方法将 GUI 组件隔离,然后使用 fixture 公开组件的验证方法。在这个过程中,您了解了对正常情况下的场景(所有事务都合乎逻辑)以及无法预见场景下(包括意外操作)进行测试是多么简单。总之,你只需要知道场景和组件在其中起到了作用。使用 TestNG-Abbot 方便的 fixture 对象可以很轻易地改变组件的行为。