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

发布于:2025-06-26 ⋅ 阅读:(19) ⋅ 点赞:(0)

📅 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()
        {
            // Arrange
            var service = new PostService(_context);

            // Act
            var result = await service.GetAllPostsAsync();

            // Assert
            Assert.NotNull(result);
            Assert.Equal(2, result.Count());
        }

        [Fact]
        public async Task GetPostByIdAsync_ReturnsCorrectPost()
        {
            // Arrange
            var service = new PostService(_context);

            // Act
            var result = await service.GetPostByIdAsync(1);

            // Assert
            Assert.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)
  • 准备作品集展示

网站公告

今日签到

点亮在社区的每一天
去签到