差異處

這裏顯示兩個版本的差異處。

連向這個比對檢視

java:expect4j [2017/08/19 23:33]
java:expect4j [2023/06/25 09:48] (目前版本)
行 1: 行 1:
 +{{tag>​java}}
 +====== Expect4J ======
 +在linux中,我們可以透過expect將流程給自動化,我們也可以將它拿來做console的自動化測試工具。多虧某些好心人士,將它porting到java上,叫[[http://​code.google.com/​p/​expect4j/​|Expect4J]]。我把它拿來測試軟體的安裝流程,接下來我用範例告訴大家該如何使用。在我的範例中,主要的類別為:​
 +  * **ConsoleAutomationFixture**:​ 負責處理Expect相關操作。
 +  * **MyInstallerAutomationFixture**:​ extedns ConsoleAutomationFixture去透過Expect處理Installer相關操作。
 +===== ConsoleAutomationFixture ​ =====
 +我將重複使用到的expect操作寫成ConsoleAutomationFixture類別,讓不同的testcases可以重複使用它。包含:​
 +  * **expectString**:​ 做某些操作後,期待待測程式所要顯示的字串。
 +  * **sendEnter**:​ 發送Enter給待測程式。
 +  * **sendCtrlC**:​ 發送Ctrl+C去強制離開程式,一般用於發生非期待事件使用。我根據installer是否有正常執行完去決定要不要送Ctrl+C。
 +  * **sendString**:​ 發送字串給待測程式。
 +  * **setTimeout**:​ 設定expectString的timeout時間。某些操作需要些時間才有會有response,可以透過設定timeout給它一個合理等待時間。
 +  * **resetTimeout**:​ 將timeout回復到預設值,10秒。
 +<code java>
 +import static org.junit.Assert.assertTrue;​
  
 +import org.junit.After;​
 +
 +import expect4j.Expect4j;​
 +
 +abstract public class ConsoleAutomationFixture {
 + protected Expect4j mExpect = null;
 + @After
 + public void tearDown() throws Exception {
 + if (mExpect != null) {
 + mExpect.close();​
 + System.out.println("​Exit the installer."​);​
 + }
 + }
 + protected void expectString(String aString) throws Exception {
 + assertTrue("​Expect string dones'​t display: "​+aString,​ mExpect.expect(aString) > -1);
 + }
 + protected void sendEnter() throws Exception {
 + mExpect.send("​\r\n"​);​
 + }
 + protected void sendCtrlC() throws Exception {
 + mExpect.send("​\003"​);​
 + }
 + protected void sendString(String aStr) throws Exception {
 + mExpect.send(aStr);​
 + sendEnter();​
 + }
 + protected void setTimeout(int aTimeout){
 + mExpect.setDefaultTimeout(aTimeout*1000);​
 + }
 + protected void resetTimeout(){
 + mExpect.setDefaultTimeout(Expect4j.TIMEOUT_DEFAULT);​
 + }
 +}
 +</​code>​
 +===== MyInstallerAutomationFixture =====
 +這個類別我只展示launchInstaller method給大家看,其它都屬於**機密**。launchInstaller做的事情,就是透過ExpectUtils.spawn去執行installer執行檔,並將建立的Expect4J物件設置到mExpect中。即使是一個shell script也是可以透過Expect4J做測試。而在建立Expect4J物件後,我所期望installer會出現的字串是**Preparing to install...**,藉此就可以確認是否有正常執行。假如你要launch installer需要較長的時間,可以透過setTimeout去延長等待時間。
 +<code java>
 +public class MyInstallerAutomationFixture extends ConsoleAutomationFixture {
 + protected void launchInstaller(String aInstaller) throws Exception {
 + File installer = new File(aInstaller);​
 + installer.setExecutable(true);​
 +
 + mExpect = ExpectUtils.spawn(aInstaller);​
 + expectString("​Preparing to install..."​);​
 + }
 +}
 +</​code>​
 +===== Summary =====
 +這個範例中我僅使用到Expect4J執行command的使用方式,它還支援SSH、Telnet、Socket。如果之後有機會再分享給大家,希望我所撰寫的ConsoleAutomationFixture對大家有幫助!
 +
 +=====    =====
 +----
 +\\
 +~~DISQUS~~