Tcl / Tk - 自动化GUI测试

时间:2011-06-06 21:40:46

标签: testing automated-tests tcl tk gui-testing

我想自动测试我的GUI。我经历了以下post但如果有人可以发布以下示例的示例测试代码,那么我将更容易理解。

以下是我的简单 Hello World 代码。

namespace eval Gui {
}

proc Gui::hello {} {
  toplevel .hello
  wm title .hello "Hello" 
  wm resizable .hello 0 0 ;# not resizable

  # create a frame to hold the check widgets 
  set f [frame .hello.boolean -borderwidth 10] 
  pack $f -side top

  # OK and Cancel buttons 
  button .hello.ok -text "OK" -command [list Gui::Ok .hello ]
  button .hello.cancel -text "Cancel" -command [list Gui::cancel .hello ]
  pack   .hello.cancel .hello.ok -side right

  bind .hello <Return> {Gui::Ok .hello ; break}
  bind .hello <Escape> {Gui::cancel .hello ; break}
}

proc Gui::Ok { arg } { 
  set x [list puts "Hello world!"]
  eval $x 
  destroy $arg
}

proc Gui::cancel { arg } { 
  destroy $arg
}

#-------------------------------------------------------------------
# Gui main window  
#-------------------------------------------------------------------
proc Gui::initialize { } {
  # build the frame which contains menu options 
  frame .mbar -relief raised -bd 2
  frame .mdummy -width 200 -height 240
  pack .mbar .mdummy -side top -fill x 

  # menu options 
  menubutton .mbar.command -text Command -underline 0 -menu .mbar.command.menu
  pack .mbar.command -side left

  # menu under command options 
  menu .mbar.command.menu -tearoff 0
  .mbar.command.menu add command -label "Hello..." -command [list Gui::hello]
}

#-------------------------------------------------------------------
# main code
#-------------------------------------------------------------------
Gui::initialize

我想测试Command -> Hello ... -> OK并查看它是否输出Hello world!。如果有人可以发布模拟这些点击的示例代码并自动进行测试,那就太棒了。

1 个答案:

答案 0 :(得分:3)

使按钮表现得像点击它的最简单方法是使用其invoke方法:

.hello.ok invoke

当然,您还必须捕获该调用的结果;在测试时写入stdout并不是世界上最有用的东西(除非你在另一个进程中包装测试工具并且......好吧,让我们把它留作更多的工作)。重构代码,以便在测试GUI部分时可以使用不同的后端,这将对您有所帮助。

也可以将方法调用的级别降低到使用event generate开始伪造事件的程度。这是更多的工作,因为你不能只生成鼠标点击和按键;您还必须综合<Enter><FocusIn>事件,以便Tk的小部件正确地自行设置。这是一个示例(-when tail将事件放在事件队列的末尾):

event generate .hello.ok <Enter> -when tail
event generate .hello.ok <ButtonPress-1> -when tail
event generate .hello.ok <ButtonRelease-1> -when tail

你甚至可以直接生成相对于顶层或整个根窗口定位的事件(尽管Tk只会在内部传递它们;它不会将事件发送到其他应用程序,因为它会相当粗鲁)但我如果你不需要他们,建议你离开岗位,因为他们会使你的代码非常脆弱(通常不重要),比如详细的字体变化。

测试GUI时祝你好运。做得好很难。通过传入脚本在适当的位置配置为参数(在Tcl中非常简单,并且等同于在其他语言中完成的“模拟”之类的操作)来制作代码以使GUI与后端分离将有助于实现阻止你必须立刻测试一切。这将有助于保持理智。

相关问题