2

私は、ASP.NET MVC を使用する際のテスト可能な設計についてかなり深く理解しており、その理解を ServiceStack を使用したテスト可能なサービスの構築に適用することに成功しています。しかし、パズルの非常に重要なピースの 1 つがわかりません。JsonServiceClient に依存する MVC アクションを単体テストするにはどうすればよいでしょうか? JsonServiceClient を独自の抽象化でラップできることは理解していますが、ServiceStack ベースのソリューションはありますか?

たとえば、DTO を使用して惑星のリストをフェッチする不自然なサービスを提供します。

public class PlanetsService : Service
{
    public IRepository Repository { get; set; } // injected via Funq

    public object Get(PlanetsRequest request)
    {
        var planets = Repository.GetPlanets();

        return new PlanetsResponse{ Planets = planets };
    }
}

JsonServiceClient を使用してデータを取得し、いくつかの作業を行ってから、惑星リストを含むビュー モデルを含むビューを返す単純な MVC アクションがあるとします。

public class PlanetsController : Controller
{
    private readonly IRestClient _restClient; // injected with JsonServiceClient in AppHost

    public PlanetsController(IRestClient restClient)
    {
        _restClient = restClient;
    }

    public ActionResult Index()
    {
        var request = new PlanetsRequest();
        var response = _restClient.Get(request);

        // maybe do some work here that we want to test

        return View(response.Planets);
    }
}

単体テストで DirectServiceClient を IRestClient として使用する道を歩み始めましたが、DirectServiceClient.Get(IRequest リクエスト) は実装されていません (NotImplementedException をスローします)。私のテストは NUnit を使用しており、ServiceStack の TestBase から継承しています。

[TestFixture]
public class PlanetsControllerTests : TestBase
{
    [Test]
    public void Index_Get_ReturnsViewResult()
    {
        var restClient = new DirectServiceClient(this, new ServiceManager(typeof(PlanetsService).Assembly));
        var controller = new PlanetsController(restClient);
        var viewResult =  controller.Index() as ViewResult;

        Assert.IsNotNull(viewResult);
    }

    protected override void Configure(Funq.Container container)
    {
        // ...
    }
}

だから私は本当の質問は次のとおりだと思います: DirectServiceClient は実際に IRestClient の単体テストに提供できますか? ServiceStack は、ASP.NET MVC で ServiceStack を使用する開発者にとって一般的なシナリオであると私が想定する戦略を提供しますか? 私は ServiceStack の提供範囲外で作業しているのでしょうか? JsonServiceClient を非表示にする独自の抽象化をコーディングする必要があるのでしょうか?

オンラインで推奨事項を探すのに多くの時間を費やしましたが、エンドツーエンドの統合テストの例はたくさんありますが、単体テストでやろうとしていることに固有のものはないようです.

4

1 に答える 1

0

の独自のモック実装を作成することはできませんIRestClientか? それとも、RhinoMock のようなものを使用してインターフェイスをモックし、期待値と応答を設定したほうがよいでしょうか?

たとえば、RhinoMock を使用すると (実際の構文についてはわかりませんが、何が起こっているかは明らかなはずです):

[Test]
public void Index_Get_ReturnsViewResult()
{
    var restClient = MockRepository.GetMock<IRestClient>();
    var controller = new PlanetsController(restClient);
    restClient.Expect(c => c.Get(null)).IgnoreArguments().Return(new PlanetsResponse{ /* some fake Planets */ });
    var viewResult =  controller.Index() as ViewResult;

    Assert.IsNotNull(viewResult);
    // here you can also assert that the Model has the list of Planets you injected...
}
于 2013-08-04T15:43:03.917 に答える