在项目解决方案下新增xunit测试项目
修改web api项目的Program为部分类
接下来和官方文档有点区别,在测试项目中直接引用web api项目即可
现在就可以添加我们的测试类使用HttpClient调用接口进行测试了
using System.Net;
using System.Text;
using Andy;
using Andy.Models;
using AutoFixture;
using Microsoft.AspNetCore.Mvc.Testing;
using Newtonsoft.Json;
namespace AndyTest
{
public class DefaultWebApplicationFactoryTest : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
private readonly IFixture _fixture;
public DefaultWebApplicationFactoryTest(WebApplicationFactory<Program> factory)
{
_factory = factory;
_fixture = new Fixture();
}
[Fact]
public async Task GetAll_Query_ReturnOkAndListStaff()
{
//Arrange
var httpClient = _factory.CreateClient();
//Purchase purchase = _fixture.Create<Purchase>();
//purchase.CustomerPurchaseNo = _fixture.Create<string>();
//Purchase purchase = new();
Purchase purchase = _fixture.Build<Purchase>().With(_ => _.Id, 0).Create();
//purchase.CustomerPurchaseNo = "22";
string jsonContent = JsonConvert.SerializeObject(purchase); // 如果你使用的是 Newtonsoft.Json
StringContent content = new(jsonContent, Encoding.UTF8, "application/json");
//act
var response = await httpClient.PostAsync("/api/Purchase/Add", content);
//Assert
//校验状态码
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
//校验用户
//var users = await response.Content.ReadFromJsonAsync<List<Staff>>();
//Assert.NotNull(users);
}
}
}
使用了AutoFixture生成随机数,有兴趣的可以自己了解下
然后我们跑一下code runsh’的代码测试覆盖率工具