LoginSignup
3
7

More than 5 years have passed since last update.

Xamarin.Formsで単体テスト

Last updated at Posted at 2017-05-09

Xamarin.FormsのPCLのユニットテストをやってみる。

なお、PCLでテストできるのはロジック部分のみ。
UIやプラットフォーム固有のもの(デバイスまわりとか)をテストする場合は、各プラットフォーム向けの単体テスト用プロジェクトを作成する必要あり。

単体テスト用プロジェクトを作成

[その他][.NET]にある[NUnit ライブラリ プロジェクト]を選択して新規プロジェクトを作成する。

new_project.png

参照を追加

担当テスト用プロジェクトの[参照]に、テスト対象にするPCLプロジェクトを追加する。

edit_reference.png

こんな感じ。

project_tree.png

テストモジュール作成

まず、テストしたいクラスはこれ。
これはPCLプロジェクトにある。

MyService.cs
namespace MyApp.Services
{
    public class MyService
    {
        public string Greet()
        {
            return "Hello from MyService.";
        }
    }
}

で、単体テスト用プロジェクトに、Test.csをリネームするなりして、このような↓↓↓クラスを作成。

MyServiceTest.cs
using NUnit.Framework;
using System;

using MyApp.Services;

namespace MyApp.UnitTest
{
    [TestFixture()]
    public class MyServiceTest
    {
        [Test()]
        public void TestGreet()
        {
            MyService service = new MyService();
            Assert.AreEqual("Hello from MyService.", service.Greet());
        }
    }
}

テスト実行

単体テスト用プロジェクトを選択した状態で、メニューバーの[実行][単体テストを実行する]を選択する。

run_unit_test.png

するとテストが実行され、結果が[テスト結果]ペインに表示される。

test_result.png

グリーンです。OKですね。

とりあえずは以上です。

こちらを参考にしました

Testing with Xamarin Forms
https://forums.xamarin.com/discussion/21504/testing-with-xamarin-forms

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7