当前位置: 首页 > 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)
  • 准备作品集展示

相关文章:

  • 淄博外贸网站建设中国足球世界排名
  • 网站备案备的是域名还是空间爱战网关键词挖掘查询工具
  • 电子商务网站开发 php防疫测温健康码核验一体机
  • 蛋糕网站建设毕业论文深圳优化seo排名
  • 温岭网站制作新余seo
  • 公司做个网站好还是做公众号好电商网站网址
  • 在uni-app build的index.html 中加入 <mate,和title 等标签内容 内容
  • 《大模型 Agent 应用实战指南》第2章:商业目标与 Agent 能力边界定义
  • 【评估指标】MAP@k (目标检测)
  • 探索解析C++ STL中的 list:双向链表的高效实现与迭代器
  • Linux学习笔记:PCIe内核篇(3):DPC服务
  • 浪潮存储单卷单LUN不能超过64T、128T解决方法
  • 领域驱动设计(DDD)【13】之重构中的坏味道:深入理解依恋特性(Feature Envy)与表意接口模式
  • 深入浅出:RocketMQ与Kafka的双剑合璧,实现高可用与高吞吐
  • 计算机网络-----详解HTTP协议
  • 用Python做一个手机镜头
  • GitHub中openmmlab和Detectron2的区别
  • 打造灵活强大的PDF解析管道:从文本提取到智能分块的全流程实战
  • Java编程中的单例模式
  • 微信点餐小程序—美食物
  • python学智能算法(十六)|机器学习支持向量机简单示例
  • ETH节点各个服务应用的作用
  • HarmonyOS5 折叠屏适配测试:验证APP在展开/折叠状态下的界面自适应,以及会出现的问题
  • 【sgMoreMenu】自定义组件:“更多操作⌵”上下文关联按钮)下拉菜单。可用于表格操作列显示不下折叠的更多操作下拉框。
  • WeakAuras Lua Script [ICC BOSS 12 - The Lich King]
  • Transformer中核心机制的讲解:位置编码,注意力机制优化!