プラグインのテストコードを書く(ショートカット編:v3.3)

プラグインのテストコードを書く(コマンド編:v3.3) - Fly me to the Juno!に引き続きテストコードの型シリーズ。以外に簡単にいけちゃいそう。今回はショートカット編。題材もKenichi Takahashi氏のFontSizeChanger。リポジトリ

https://eclipse-study.svn.sourceforge.net/svnroot/eclipse-study/EasyFontChanger/branches/TRY-Active-View/

です。
今回のお題はショートカット-コマンド間の実行(Binding-Command)です。ショートカットとコマンドの関係はplugin.xmlに次のように書きます。

<extension
  point="org.eclipse.ui.commands">
 <command
   categoryId="net.shu-cream.eclipse.font.category1" (2)
   id="net.shu_cream.eclipse.font.large" (1)
   name="Large">
 </command>
</extension>
<extension
 point="org.eclipse.ui.bindings">
  <key
   commandId="net.shu_cream.eclipse.font.large" (1)
   contextId="org.eclipse.ui.contexts.dialogAndWindow"
   schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
   sequence="M1+M3+;">
  </key>
</extension>

(1)がCommandとHandlerを結びつけるキーで、(2)のカテゴリーを設定しないと環境によってはせっかく設定したCommandが動作しなくなることがあるようです。
WindowsだとM1はCtrlキー、M3はAltキーに相当します。*1で、今回書いたテストコードはこんな感じ。

  @Test
  public void このクラスがショートカットに登録されているか() throws Exception {
    IBindingService service = (IBindingService) PlatformUI.getWorkbench().getService(IBindingService.class);
    TriggerSequence[] sequences = service.getActiveBindingsFor("net.shu_cream.eclipse.font.large");
    assertEquals(1, sequences.length);
    KeyStroke s = (KeyStroke)sequences[0].getTriggers()[0];
    System.out.println(s.format());
    assertEquals("Ctrl+Alt+;",sequences[0].format());
  }

ありがたいことにorg.eclipse.ui.keys.IBindingServiceにはコマンドのIDからアクティブなキーバインドを取得できるgetActiveBindingsFor(String)というAPIが用意されているんですね。これでキーバインドを取得して、ショートカットキーの文字列を比較すれば一応テストできます。*2
IBindingServiceクラスには他にBinding IBindingService#getPerfectMatch(TriggerSequence)というAPIがあり、BindingクラスからgetParametarizedCommand()を取得すると前述のコマンドなので、それを実行してあげると(Binding - Command - Handler)の一連の流れを実行することができます。

*1:他のプラットフォームだとどうなのかなど、詳しい情報をお探しの方は[http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/extension-points/org_eclipse_ui_bindings.html:title]のkey - sequenceの辺りを見てください。

*2:マルチOSには未対応