コールバックメソッドを利用することよりも、Rxによってメソッドチェーンを記述することで、
コードが分散せず一貫したコードが書けるように思えます。
もちろん、ユニットテストは必要なのですがいかんせんWindowsPhoneはテストフレームワークが公式に
提供されているわけでは無いらしく、色々と面倒くさいです。
どうにか、記述する方法を発見したので公開。と言っても、neueccさんのところで公開されていますが・・・。
1.WindowsPhone7.1のプロジェクトを作る
作りましょう。
2.テスト対象のコードを記述する。
今回は、引数のURLにアクセスを行いページの内容をstringで取得するメソッドを用意しました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AsyncAccess | |
{ | |
public IObservable<string> requestHttpGET(string url) | |
{ | |
var request = WebRequest.Create(url); | |
return Observable.FromAsyncPattern<WebResponse>( | |
request.BeginGetResponse, request.EndGetResponse) | |
.Invoke() | |
.Select(resp => | |
{ | |
using (var stream = resp.GetResponseStream()) | |
using (var st = new StreamReader(stream)) | |
{ | |
return st.ReadToEnd(); | |
} | |
}).ObserveOnDispatcher() | |
.Select(content => | |
{ | |
return content; | |
}); | |
} | |
} |
3.テストプロジェクトを作成する。
3.1.
まずは、WindowsPhone7.1のプロジェクトを作ります。
3.2.
http://www.jeff.wilcox.name/2011/06/updated-ut-mango-bits/ で配布されているファイルをダウンロードし、参照に追加します。
3.3.
テスト対象のプロジェクトを参照に追加します。
3.4.
http://blog.richardszalay.com/2011/08/08/writing-asynchronous-unit-tests-with-rx-and-the-silverlight-unit-testing-framework/
こちらに記述されている WorkItemTestScheduler と ObservableExtensions を追加します。
4. テストを記述する
今回は次のコードを用いてURLに適切にアクセスができているのかを確認します。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestClass] | |
public class AsyncAccessTest : SilverlightTest | |
{ | |
[TestMethod, Asynchronous] | |
public void Test_AsyncHTTPGET_Success() | |
{ | |
var accesser = new AsyncAccess(); | |
accesser | |
.requestHttpGET("http://www.google.co.jp"). | |
ObserveOnTest(this). | |
Subscribe(content => | |
{ | |
Assert.IsNotNull(content); | |
TestComplete(); | |
}); | |
} | |
[TestMethod, Asynchronous] | |
public void Test_AsyncHTTPGET_InvalidURL() | |
{ | |
var accesser = new AsyncAccess(); | |
accesser | |
.requestHttpGET("http://localhost"). | |
ObserveOnTest(this) | |
.Subscribe | |
(_ => Assert.Fail(), | |
e => | |
{ | |
Assert.IsNotNull(e); | |
TestComplete(); | |
}); | |
} | |
} |
5. 実行する
ソリューションを右クリックし、「スタートアッププロジェクトの設定」を選び、
テストプロジェクトをスタートアッププロジェクトに設定します。
![]() |
成功したパターン |
![]() |
失敗したパターン |
6.所感
このやり方を発見するまでに時間がかかってしまった。結局やりたいことは例によってテストやビルドの自動化。http://blogs.msdn.com/b/francischeung/archive/2012/01/03/running-windows-phone-unit-tests-via-msbuild.aspx
このサイトを見る限りMSBuildを利用して、コマンドラインからテストの実行ができるらしい? ので、いつもどおり
Jenkinsさんと組み合わせてCI環境を作るところまでやりたいです。