测试控制器的Get()方法的最佳方法

时间:2018-01-25 14:52:20

标签: c# unit-testing asp.net-core nunit

我有以下带有get()方法的构造函数,我需要测试此方法是否可以通过NUnit正常工作。

public ConsumersController(IProvider<Consumer> provider)
{
  this.provider = provider;
}

/// <summary>
/// Get the list of consumers that you are allowed to see and serve
/// </summary>
/// <response code="200">Returns the consumers you are allowed to see and serve</response>
[HttpGet]
[ProducesResponseType(typeof(IEnumerable<Consumer>), 200)]
[Produces(typeof(IEnumerable<Consumer>))]
[SwaggerResponse((int)HttpStatusCode.OK, Type = typeof(IEnumerable<Consumer>))]
public IEnumerable<Consumer> Get()
{
  return this.provider.GetAll();
}

我是根据此链接Testing controller logic in ASP.NET Core创建此代码的,但我不知道它是否正确,测试未通过。 提前谢谢。

[TestFixture]
public class ConsumerTest
{
    private readonly HttpClient consumerHttp;

    private readonly ConsumersController consumerControl;

    [Test]
    public async Task Get_ConsumersController()
    {
        var result = this.consumerControl.Get();
        var response = await consumerHttp.GetAsync("http://localhost:9000/consumers");
        response.EnsureSuccessStatusCode();

        var consumerList = JsonConvert.DeserializeObject<IEnumerable<Consumer>>(await response.Content.ReadAsStringAsync());
        var consumerTest = consumerList.First();

        Assert.AreEqual(result.First().Name, consumerTest.Name);
    }
}

1 个答案:

答案 0 :(得分:0)

感谢您的回答。实际上它没有使用MOQ库,并且使用Async时出错。我用这段代码得到了它。

[Test]
public void Get_ReturnsAConsumer_WithAListOfIProvider()
{
  var mockRepo = new Mock<IProvider<Consumer>>();
  mockRepo.Setup(repo => repo.GetAll()).Returns(GetConsumers());

  var controller = new ConsumersController(mockRepo.Object);
  var result = controller.Get();

  Assert.IsAssignableFrom<List<Consumer>>(result);
  Assert.AreEqual(1, result.Count());
}