如何使用 XUnit 对 Web API 控制器进行单元测试 [英] How to unit test a Web API controller using XUnit
问题描述
我正在尝试使用 XUnit 在我的 Web API 中对控制器中的方法进行单元测试.该方法的作用是从数据库中按 ISBN 获取单个标题.我在单元测试期间遇到的问题是,我不确定如何插入必须执行测试的虚拟数据,以及 Assert 函数的工作原理.
I am trying to unit test a method within my controller in my Web API using XUnit. The role of the method is to get a single title, by ISBN, from the database. The issue I came across during unit testing is that I am unsure how to insert the dummy data that I must perform the test on, as well as how the Assert function works.
TitleController.cs
[ApiController]
[Route("titlecontroller")]
public class TitleController : Controller
{
private IGtlTitleRepository _gtlTitleRepository;
public TitleController(IGtlTitleRepository gtlTitleRepository)
{
_gtlTitleRepository = gtlTitleRepository;
}
[Route("getTitle/{ISBN}")]
[HttpGet()]
public GtlTitle GetTitle(string ISBN)
{
return _gtlTitleRepository.GetTitle(ISBN);
}
}
IGtlTitleRepository.cs
public interface IGtlTitleRepository
{
GtlTitle GetTitle(string ISBN);
}
MockGtlTitleRepository.cs
public class MockGtlTitleRepository : IGtlTitleRepository
{
private readonly string _connection;
public MockGtlTitleRepository(IOptions<ConnectionStringList> connectionStrings)
{
_connection = connectionStrings.Value.GTLDatabase;
}
private List<GtlTitle> _titleList;
public GtlTitle GetTitle(string ISBN)
{
using (var connection = new SqlConnection(_connection))
{
connection.Open();
return connection.QuerySingle<GtlTitle>("GetTitleByISBN", new { ISBN }, commandType: CommandType.StoredProcedure);
}
}
}
对了,至于我的测试代码,我能够写出下面的代码,但是正如我上面所说的,我想不出合适的方法来测试该方法.
Right, as for my test code, I was able to write the following code, but as I said above, I can't figure out a proper way to test the method.
public class UnitTest1
{
[Fact]
public void Test1()
{
var repositoryMock = new Mock<IGtlTitleRepository>();
var title = new GtlTitle();
repositoryMock.Setup(r => r.GetTitle("978-0-10074-5")).Returns(title);
var controller = new TitleController(repositoryMock.Object);
var result = controller.GetTitle("978-0-10074-5");
// assert??
repositoryMock.VerifyAll();
}
}
在这个单元测试中应该做什么才能正确测试方法?
What should be done within this unit test in order to properly test the method?
GtlTitle.cs
public class GtlTitle
{
public string ISBN { get; set; }
public string VolumeName { get; set; }
public string TitleDescription { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PublisherName { get; set; }
}
推荐答案
在进行测试之前,我建议您在代码中更新一些内容:
Before going to testing, there are a few things I recommend updating in your code:
- 使您的存储库方法和控制器操作异步(因此 Web 服务器可以在等待先前调用的数据库往返时处理请求)
- 使用
ActionResult
作为动作返回类型.通过这种方式,您可以向客户端发送不同的 http 状态代码. - 未找到标题时返回 404 NotFound 状态代码,而不是返回以
null
作为负载的成功结果. - 考虑对 API 端点使用 RESTful 方法.例如.titles 资源的基本 uri 应该类似于
api/titles
- 不要指定
getTitle
来获取标题端点,因为您知道 HTTP 动词将哪个端点映射到 (GET) 和基本资源 url (api/titles).
- Make your repository methods and controller actions async (thus web server can process requests while waiting for database roundtrips for previous calls)
- Use
ActionResult
as an action return type. This way you can send different http status codes to the client. - Return 404 NotFound status code when title not found instead of returning successful result with
null
as payload. - Consider using a RESTful approach for API endpoints. E.g. base uri for titles resource should be something like
api/titles
- Don't specify
getTitle
for getting title endpoint, because you know HTTP verb which endpoint is mapped to (GET) and base resource url (api/titles).
应用这些注释:
[ApiController]
[Route("api/titles")]
public class TitleController : Controller
{
private IGtlTitleRepository _gtlTitleRepository;
public TitleController(IGtlTitleRepository gtlTitleRepository)
{
_gtlTitleRepository = gtlTitleRepository;
}
[HttpGet("{ISBN}")] // GET api/titles/{ISBN}
public async Task<ActionResult<GtlTitle>> GetTitle(string ISBN)
{
var title = await _gtlTitleRepository.GetTitle(ISBN);
if (title == null)
return NotFound();
return title;
}
}
测试标题检索成功:
[Fact]
public async Task Should_Return_Title_When_Title_Found()
{
var repositoryMock = new Mock<IGtlTitleRepository>();
var title = new GtlTitle();
repositoryMock.Setup(r => r.Get("978-0-10074-5")).Returns(Task.FromResult(title));
var controller = new TitleController(repositoryMock.Object);
var result = await controller.GetTitle("978-0-10074-5");
Assert.Equal(title, result.Value);
}
未找到标题时:
[Fact]
public async Task Should_Return_404_When_Title_Not_Found()
{
var repositoryMock = new Mock<IGtlTitleRepository>();
repositoryMock.Setup(r => r.Get("978-0-10074-5")).Returns(Task.FromResult<GtlTitle>(null));
var controller = new TitleController(repositoryMock.Object);
var result = await controller.GetTitle("978-0-10074-5");
Assert.IsType<NotFoundResult>(result.Result);
}
这篇关于如何使用 XUnit 对 Web API 控制器进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!