当前位置: 首页 > news >正文

跟着AI学习C#之项目实践Day7

📅 Day 7:单元测试 + 缓存优化 + 性能分析

✅ 今日目标:

  • 添加 单元测试项目(xUnit / Moq)
  • 测试 PostServicePostModel 的业务逻辑
  • 添加缓存机制(MemoryCache / Redis)
  • 使用 Application Insights 进行性能监控
  • 提交 Git 版本记录进度

🧪 一、添加单元测试项目(xUnit)

✅ 步骤:

  1. 在解决方案中添加 xUnit 测试项目:

    dotnet new xunit -n MyBlog.Tests
    
  2. 添加项目引用:

    dotnet add reference ../MyBlog/MyBlog.csproj
    
  3. 安装必要的 NuGet 包:

    • Microsoft.AspNetCore.Mvc
    • Moq
    • EntityFrameworkCore.Testing.Moq

✅ 示例测试类:Services/PostServiceTests.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MyBlog.Models;
using MyBlog.Services;
using Xunit;namespace MyBlog.Tests.Services
{public class PostServiceTests{private readonly ApplicationDbContext _context;public PostServiceTests(){var options = new DbContextOptionsBuilder<ApplicationDbContext>().UseInMemoryDatabase(databaseName: "TestDb_PostService").Options;_context = new ApplicationDbContext(options);// 初始化数据if (!_context.Posts.Any()){_context.Posts.AddRange(new Post { Id = 1, Title = "C# 入门", Content = "学习 C#", CreatedAt = DateTime.Now },new Post { Id = 2, Title = "ASP.NET Core 教程", Content = "构建 Web 应用", CreatedAt = DateTime.Now });_context.SaveChanges();}}[Fact]public async Task GetAllPostsAsync_ReturnsAllPosts(){// Arrangevar service = new PostService(_context);// Actvar result = await service.GetAllPostsAsync();// AssertAssert.NotNull(result);Assert.Equal(2, result.Count());}[Fact]public async Task GetPostByIdAsync_ReturnsCorrectPost(){// Arrangevar service = new PostService(_context);// Actvar result = await service.GetPostByIdAsync(1);// AssertAssert.NotNull(result);Assert.Equal("C# 入门", result.Title);}}
}

💡 小贴士:你也可以为评论、分类、搜索等功能编写测试。


🧠 二、创建 PostService(可选重构)

为了更好的测试和解耦,你可以将数据库访问逻辑封装到服务层。

✅ 创建 Services/PostService.cs

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using MyBlog.Models;namespace MyBlog.Services
{public class PostService{private readonly ApplicationDbContext _context;public PostService(ApplicationDbContext context){_context = context;}public async Task<IEnumerable<Post>> GetAllPostsAsync(){return await _context.Posts.ToListAsync();}public async Task<Post?> GetPostByIdAsync(int id){return await _context.Posts.FindAsync(id);}public async Task AddPostAsync(Post post){_context.Posts.Add(post);await _context.SaveChangesAsync();}// 可继续添加其他方法}
}

✅ 注册服务(Program.cs):

builder.Services.AddScoped<PostService>();

然后在 Razor Page 中注入使用它。


🧊 三、添加缓存优化(MemoryCache)

我们可以对文章列表进行缓存,提升首页加载速度。

✅ 修改 Pages/Posts/Index.cshtml.cs

注入 IMemoryCache

private readonly IMemoryCache _cache;public IndexModel(ApplicationDbContext context, IMemoryCache cache)
{_context = context;_cache = cache;
}public async Task<IActionResult> OnGetAsync()
{const string cacheKey = "AllPosts";if (!_cache.TryGetValue(cacheKey, out IEnumerable<Post> posts)){posts = await _context.Posts.Include(p => p.Category).ToListAsync();var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(5));_cache.Set(cacheKey, posts, cacheEntryOptions);}Posts = posts;return Page();
}

🔍 四、使用 Application Insights 进行性能分析(可选)

Application Insights 是微软提供的 APM 工具,可用于监控请求、异常、依赖项等。

✅ 步骤:

  1. 登录 Azure 并创建 Application Insights 资源。
  2. 获取 Instrumentation Key。
  3. Program.cs 中启用 AI:
builder.Services.AddApplicationInsightsTelemetry(builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]);
  1. 配置 appsettings.json
{"Logging": {"ApplicationInsights": {"LogLevel": {"Default": "Information"}}},"APPLICATIONINSIGHTS_CONNECTION_STRING": "InstrumentationKey=your-key-here"
}
  1. 部署后即可在 Azure 查看性能日志。

📦 五、提交 Git 版本

git add .
git commit -m "Day7: Added unit tests, caching and performance analysis setup"

📝 今日总结

今天你完成了:

✅ 添加并配置 xUnit 单元测试项目
✅ 实现 PostService 并完成基础逻辑测试
✅ 引入 MemoryCache 缓存文章列表提升性能
✅ 可选配置 Application Insights 监控应用性能
✅ 提交版本控制记录


📆 明日计划(Day8)

我们将进入 部署与上线阶段

  • 使用 Docker 构建容器镜像
  • 配置 GitHub Actions 自动化 CI/CD
  • 部署到本地服务器或云平台(如 Azure App Service)
  • 准备作品集展示
http://www.lqws.cn/news/519859.html

相关文章:

  • sentinel 自定义 dashboard 用户名密码
  • 第⼀个与⼤模型交互的应⽤
  • Swagger 在 Spring Boot 中的详细使用指南
  • thinkphp8之文件上传
  • 用户体验驱动的3D设计:从功能实现到情感共鸣的设计升级
  • 融合聚类与分类的退役锂电智能分选技术:助力新能源汽车产业可持续发展
  • JVM调优实战 Day 6:JVM性能监控工具实战
  • 数据结构 顺序表与链表
  • python的易家宜超市云购物系统
  • webman 利用tcp 做服务端 对接物联网
  • 使用 Spread.net将 Excel 中的文本拆分为多段
  • 注解+AOP+自动配置实现自定义starter
  • Java8 Stream流:Stream流的思想和获取Stream流
  • 深入浅出:RocketMQ与Kafka的双剑合璧,实现高可用与高吞吐
  • 服务器不支持PUT,DELETE 的解决方案
  • python爬虫框架scrapy学习记录
  • 打造属于你的AI智能体,从数据开始 —— 使用 Bright Data MCP+Trae快速构建垂直智能体
  • 量学云讲堂2025朱永海慢牛开启第58期视频课程
  • 卡萨帝发布AI深度科技:实现从守护生活到守护文明的升级
  • Linux系统之Nginx反向代理与缓存
  • Aurora MySQL 3.05/3.06/3.07版本即将停用,全局数据库升级实战指南
  • 逆序对的数量
  • 基于MATLAB的BP神经网络的心电图分类方法应用
  • pyhton基础【16】函数进阶二
  • 仿Apple官网设计风格
  • HCIA-IP路由基础
  • 鸿蒙OH南向开发 轻量系统内核(LiteOS-M)【Shell】
  • 实测对比:用 Lynx 做网页,效率比传统工具提升 270% 的底层逻辑
  • 【Oracle学习笔记】4.索引(Index)
  • 【大厂机试题解法笔记】可以组成网络的服务器