初めて単体テストを書く練習をしていますが、いくつか質問があります。何をテストしようとしているのかを説明することから始めます。
次のようなメソッドをテストしたいと思います。
public bool IsAdmin(HubCallerContext hubCallerContext)
{
return hubCallerContext.User.IsInRole("admin");
}
UserService
メソッドは、インターフェイスに接続されたクラスに実装されますIUserService
。
私は2つのテストを作成しようとしています:
- 「admin」の役割にあり、true をアサートする HubCallerContext を持つもの。
- 「ユーザー」の役割にあり、false をアサートする HubCallerContext を持つもの。
ソリューションに新しいクラス ライブラリを作成しました。ここで、テストしているプロジェクトを参照しました。NUnit と Moq をインストールし、次のようなテスト クラスを作成しました。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChatProj;
using NUnit.Framework;
using ChatProj.Controllers;
using Moq;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using ChatProj.DAL;
using ChatProj.Service_Layer;
using System.Threading.Tasks;
namespace ChatProj.Tests
{
[TestFixture]
public class Class1
{
[SetUp]
public void Setup()
{
}
[Test]
public void IsAdmin_CalledByAdmin_ReturnTrue()
{
UserService userService = new UserService();
bool result = userService.IsAdmin( ? );
Assert.IsTrue( result, "Something is wrong." );
}
[Test]
public void IsAdmin_CalledByUser_ReturnFalse()
{
UserService userService = new UserService();
bool result = userService.IsAdmin( ? );
Assert.IsFalse( result, "Something is wrong." );
}
}
}
ここで私は混乱し始めます。(IsAdmin 呼び出しのパラメーターを「?」でマークしました。そこに何を入れたらよいかわからないためです。)
モック、スタブ、フェイク、ダミーについて読んだことがありますが、定義は抽象的で、私が実際に把握することはできません。たとえば、次の定義を見つけました。
- Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
- Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
- Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
- Mocks are objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
テスト クラスを設計したので、HubCallerContext を何らかの代用にする必要があります。これは、「IsAdmin」メソッドを正しい方法でテストしていると仮定しています。
だから私の質問は:
「IsAdmin」メソッドを適切にテストしていますか?
テストを実際に機能させるにはどうすればよいですか?モックを使用しますか? その場合、それをどのように実装するかを示すか、正しい方向に向けてもらえますか? HubCallerContext が参照のためにどのように機能するかを次に示します。