7

我有这个服务:

public class PlayerService : Service
{
    public IPlayerAppService PlayerAppService { get; set; }

    public PlayerService (IPlayerAppService service)
    {
        if (service == null)
            throw new ArgumentException ("Service null");

        PlayerAppService = service;
    }

    public object Post (PlayerDTO request)
    {
        var newPlayer = new PlayerResponse ()
        {
            Player = PlayerAppService.SendPlayerLocation(request.Position.Latitude, request.Position.Longitude)
        };

        return new HttpResult (newPlayer)
        {
            StatusCode = System.Net.HttpStatusCode.Created,
            Headers =
            {
                { HttpHeaders.Location, base.Request.AbsoluteUri.CombineWith(newPlayer.Player.Id.ToString()) }
            }
        };
    }
}

我已经手动验证了位置和响应在我部署此服务时看起来是正确的。我想弄清楚如何对此进行单元测试。我写了一个这样的测试:

[TestFixture]
public class PlayerServiceTests
{
    AppHost appHost;

    [TestFixtureSetUp]
    public void TestFixtureSetUp ()
    {
        appHost = new AppHost ();
        appHost.Init ();
        appHost.Start ("http://localhost:1337/");
    }

    [TestFixtureTearDown]
    public void TestFixtureTearDown ()
    {
        appHost.Dispose ();
        appHost = null;
    }

    [Test]
    public void NewPlayer_Should_Return201AndLocation ()
    {
        // Arrange
        PlayerService service = new PlayerService (appHost.TryResolve<IPlayerAppService>());

        // Act
        HttpResult response = (HttpResult)service.Post (It.IsAny<PlayerDTO>());

        // Assert
        Assert.NotNull (response);
        Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
        Assert.AreEqual(response.Response.ToDto<PlayerResponse>().Player.Id.ToString(), response.Headers.Where(x=> x.Key == HttpHeaders.Location).SingleOrDefault().Value);
    }
}

我的单元测试运行时的 base.Request 。你对我如何从我的单元测试中填充这个有什么建议吗?

4

1 回答 1

13

您正在使用自托管 HttpListener ,就像在集成测试中一样,但您没有在集成测试中使用。

集成测试如下所示:

[Test]
public void NewPlayer_Should_Return201AndLocation ()
{
    var client = new JsonServiceClient("http://localhost:1337/") {
        ResponseFilter = httpRes => {
            //Test response headers...
        };
    }

    PlayerResponse response = client.Post(new Player { ... });
}

否则,如果您想进行单元测试,则不需要 AppHost 并且可以PlayerService像任何其他 C# 类一样测试该类,注入所有依赖项和它需要的模拟请求上下文。

[Test]
public void NewPlayer_Should_Return201AndLocation ()
{
    var mockCtx = new Mock<IRequestContext>();
    mockCtx.SetupGet (f => f.AbsoluteUri).Returns("localhost:1337/player");

    PlayerService service = new PlayerService {
        MyOtherDependencies = new Mock<IMyOtherDeps>().Object,
        RequestContext = mockCtx.Object,
    };

    HttpResult response = (HttpResult)service.Post(new Player { ... });

    //Assert stuff..
}
于 2013-02-09T21:12:54.230 回答