C#でのテスト(2) nantによるビルドの自動化
C#でのテスト(1) テスト用プロジェクト(?) - ぐるぐる〜に続いて、今回はnantを使ってビルドを自動化する。
その前に、Visual Studio上でNAntの設定ファイルのIntelliSenseを働かせるように設定しておく。
NAntをダウンロードして解凍すると、schemeフォルダの中にnant.xsdというファイルがあるので、これをVisual Studioのインストールフォルダ*1のXmlのSchemeフォルダ内にコピーする。
これで、ルート要素*2のxmlns属性にhttp://nant.sf.net/release/0.85/nant.xsdを指定することで、IntelliSenseが効くようになる*3。
NAntのビルドファイルは、default.buildとして保存する。
- ソリューション'TestSample'
- TestSample
- Properties
- 参照設定
- Tests
- UnitTest
- HelloWorldTest.cs
- UnitTest
- default.build
- HelloWorld.cs
- Program.cs
- TestSample
default.buildの内容は、出発点として以下のものを使用する。
<?xml version="1.0" encoding="utf-8"?> <!-- xmlsを指定することで、Visual Studio上でIntelliSenseが効くようになる --> <project name="TestSample" xmlns="http://nant.sf.net/release/0.85/nant.xsd"> <!-- リリース用ビルド --> <target name="build"> <!-- Releaseディレクトリが無ければ作成する --> <mkdir dir="bin/Release" unless="${directory::exists('bin/Release')}"/> <!-- デバッグモードをoffでコンパイル --> <csc target="exe" output="bin/Release/TestSample.exe" debug="false"> <sources> <!-- すべての.csファイルが対象だが、 --> <include name="**/*.cs"/> <!-- Tests以下のファイルは対象外 --> <exclude name="Tests/**/*.cs"/> </sources> </csc> </target> <!-- デバッグ用ビルド --> <target name="debug-build"> <mkdir dir="bin/Debug" unless="${directory::exists('bin/Debug')}"/> <!-- デバッグモードをonでコンパイル --> <csc target="exe" output="bin/Debug/TestSample.exe" debug="true"> <sources> <!-- 対象ファイルはリリース用ビルドと同じ --> <include name="**/*.cs"/> <exclude name="Tests/**/*.cs"/> </sources> </csc> </target> <!-- すべてのテストを実行する --> <target name="test" depends="debug-build"> <mkdir dir="bin/Test" unless="${directory::exists('bin/Test')}"/> <csc target="library" output="bin/Test/TestSample.dll"> <!-- 必要なdllとテスト対象のexeを参照する --> <references> <include name="bin/Debug/nunit.framework.dll"/> <include name="bin/Debug/TestSample.exe"/> </references> <!-- コンパイル対象ファイルはTests以下のcsファイル --> <sources> <include name="Tests/**/*.cs"/> </sources> </csc> <!-- 必要なdllをコピーする --> <copy file="bin/Debug/nunit.framework.dll" tofile="bin/Test/nunit.framework.dll"/> <!-- NUnit2を実行する --> <nunit2> <!-- プレーンテキスト形式で結果をコンソールに出力 --> <formatter type="Plain"/> <!-- コンパイルしたdllを指定する --> <test assemblyname="bin/Test/TestSample.dll"/> </nunit2> </target> </project>
このファイルのある場所でコマンドプロンプトを開き、
nant build
とすることでリリース用のビルドが指定したフォルダ以下に作成される*4。
ポイントは、excludeでTestsフォルダ以下のファイルをコンパイル対象外としていることで、そのほかには特に特別なことはしていない。
Visual Studio上ではDebugモードで開発、TestDriven.NETによるテストを行い、そのままデバッグ・実行をし、リリース用のビルドはNAntで行う。
上のファイルでテスト用のtargetも記述してあるのは、CIツールで使用することを見越して作成してある。
次はちょっとした番外編を予定している。