[Tool][Selenium IDE]Export to C#/WebDriver/MSTest

  • 7912
  • 0
  • 2015-12-28

[Tool][Selenium IDE]Export to C#/WebDriver/MSTest

前言

這件事起因於我使用FireFox 25.0.1 (最新)版本,Selenium IDE 2.4.0 (最新)版本,但是在針對 select command export 或 copy to clipboard 時,會 throw exception。


// ERROR: Caught exception [ReferenceError: selectLocator is not defined]

Ticket 的緣由可以參考:https://code.google.com/p/selenium/issues/detail?id=6622

因為想找到問題,所以我 trace 了一下各語言 formatter 的 source code ,然後也找到了原因在哪。但是各語言的 formatter template 是 readonly 的,所以我無法直接從 source code 來 fix bug。

後來 TonyQ 提醒了一下,source code 是可以改的,我才突然想到,雖然原本的 template 是 readonly 的,但是 Selenium IDE 是允許新增自訂的 formatter ,因此新增了一版 fix 掉 select 的 bug ,也可以正常運作。

 

Fix Select Command Bug

問題的原因跟修復方式相當簡單,只要把 select 的 function parameter 從 label 改成 selectLocator 即可,如下:


WDAPI.Element.prototype.select = function(selectLocator) {
  if (selectLocator.type == 'index') {
    return "new SelectElement(" + this.ref + ").SelectByIndex(" + selectLocator.string + ")";
  }
  if (selectLocator.type == 'value') {
    return "new SelectElement(" + this.ref + ").SelectByValue(" + xlateArgument(selectLocator.string) + ")";
  }
  return "new Select(" + this.ref + ").SelectByText(" + xlateArgument(selectLocator.string) + ")";
};

 

新增自訂的 Formatter for MSTest

然而,也因為可以新增自訂的 formatter ,所以之前常困擾我們的一個問題: Export 只支援 NUnit 這件事,就顯得相當簡單就可以解決了。

因此就順手自己寫了一版 for C#/WebDriver/MSTest 的版本,供大家參考一下。

我只有因應需求改了幾個簡單的地方,主要是using namespace的部份,以及 TestClass/TestMethod/TestInitialize/TestCleanUp 標記的部分。另外我把 verify command 會加上 try/catch 的部份拔掉了。

 

使用自訂 Formatter 方式

要使用自訂 Formatter 相當簡單:

  1. 打開 Selenium IDE,選擇 Options
    clip_image001
  2. 選擇 Formats 的頁籤,按下 Add
    clip_image001[4]
  3. 給個 Custom Formatter 的名字,如 C#/WebDriver/MSTest ,把附件中的內容貼上去,按下 Save 即可。
  4. 接著就可以在 Clipboard Format 中,看到我們自訂的 Format 。
    clip_image001[6]
    也可以在 Export 中看到自訂的 Format ,如下:
    clip_image001[8]

拿到的 testing code 直接貼到測試專案中,就可以運作了。另外記得 NuGet 要安裝 Selenium WebDriver 以及Selenium WebDriver Support Classes ,沒有裝 Support Classes 的話,SelectElement 型別會找不到,namespace 是在 OpenQA.Selenium.Support.UI


using OpenQA.Selenium.Support.UI;

clip_image002

 

結論

Selenium 一向是好物,除了 Selenium IDE 簡單好用到誰都可以操作以外,匯出的彈性還是很大的,執行起來也相當輕鬆。搭配 BDD 來設計 Web UI 上的 Acceptance testing 更是美妙。

當可以自訂 formatter 時,就代表著針對每個 command 我們可以自行定義 export 的方式,如 PHP, javascript, 甚至 wiki 等等,或是要搭配 xUnit 等其他 testing framework。不過,匯出後要能執行,還是得有 selenium 的 package API 支援,才會比較方便。

希望這篇文章可以讓大家更快樂地使用 Selenium IDE ,以及更方便地轉換成你需要的測試程式囉。


blog 與課程更新內容,請前往新站位置:http://tdd.best/