如何对这种方法进行单元测试?

时间:2015-04-08 12:58:01

标签: c# unit-testing .net-4.5 moq mstest

我有一个方法,它也是我尝试编写测试的方法:

public IPlayerResponse GetPlayerStats(IPlayerRequest playerRequest)
{
    string playerId = playerRequest.PlayerId;

    string requestUri = playerId + "/evaluate";

     var request = new HttpRequestMessage(HttpMethod.Post, requestUri)
                                {
                                    Content = new StringContent
            (JsonConvert.SerializeObject(playerRequest),
             System.Text.Encoding.UTF8,
            "application/json")
          };

      var response = _client
    .SendAsync(request, CancellationToken.None)
    .Result;
     var responseContent = response.
    Content
    .ReadAsStringAsync()
    .Result;



    var playerResponseModel =    
    JsonConvert.DeserializeObject<PlayerResponseModel>(responseContent);
    var playerResponse = _mapper
.Map<IPlayerResponse>(playerResponseModel);

return playerResponse;
 }

请求界面:

public interface IPlayerRequest
    {
        IEnumerable<IPlayerStatsItem> Items { get; set; }
        string PlayerId { get; set; }
    }

我计划为此方法编写测试并发送IPlayerRequest的示例数据以获取针对已部署端点的响应。我已准备好TestSetup来命中端点。

模拟IPlayerRequest并用一些数据填充它以获得响应的理想方法是什么?

3 个答案:

答案 0 :(得分:1)

还有另一种语法(Moq functional specifications)用于为这样的情况设置模拟:

var mockRequest = Mock.Of<IPlayerRequest>(
    r =>
    r.PlayerId == "MOCKID" &&
    r.Items == new List<IPlayerStatsItem>()); //or whatever needed);

还有Mocks.Of<T>,因此您可以r.Items == new List使用r.Items == Mocks.Of<IPlayerStatsItem>()而不是{{1}}。这将产生无限的模拟列表。

答案 1 :(得分:0)

在测试设置中的调用方法中,只需创建一个私有类。

private class PlayerRequest : IPlayerRequest
{
    //hard code your test values you are passing in
    public string Name {get; private set;}
    public PlayerRequest() {
         Name = "MockName";
    }
}

然后致电:

var response = obj.GetPlayerStatus(new PlayerRequest());

编辑以添加moq版本,如果这是您尝试使用的:

var mockRequest = new Mock<IPlayerRequest>();
mockRequest.SetupGet(pr => pr.Name).Returns("MOCKNAME");

var response = obj.GetPlayerStatus(mockRequest.Object);

答案 2 :(得分:0)

我缺乏使用模拟框架作为Moq或RhinoMocks的经验,这是关于MS伪造的东西,这对于存根(模拟)和放大器来说非常有用。匀化

如果您有Visual Studio Premium或Ultimate,您可以随时使用MS假货! (https://msdn.microsoft.com/en-us/library/hh549175.aspx

只需将您尝试使用存根替换的界面存根,这在帖子中有解释。

然后你可以按如下方式使用它:

[TestMethod]
public void TestSomething()
{
    // Arrange
    // Stub for PlayerRequest
    StubIPlayerRequest playerRequest = new StubIPlayerRequest
    {
        ItemsSetIEnumerableOfIPlayerStatsItem = items => { }, // Setters do nothing in this example.
        ItemsGet = () => new List<StubIPlayerStatsItem>(), // Also stubbed the other interface here, not required.
        PlayerIdGet = () => "Returns a string",
        PlayerIdSetString = s => { }
    };

    // Act

    // Assert whatever you need.
}

如果您需要在不下载库的情况下进行单元测试,这是一个非常简单直接的存根和填充框架。

关于差异的一些有趣讨论 - &gt; Mock framework vs MS Fakes frameworks

HTH。