.net core web api单元测试

在项目解决方案下新增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’的代码测试覆盖率工具
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值