IM/backend/IMTest/Service/GroupServiceTest.cs
nanxun 77db20dc38 前端:
1、完善创建群聊逻辑
后端:
1、完善群聊相关接口
2026-02-11 22:44:28 +08:00

94 lines
3.3 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using AutoMapper;
using IM_API.Dtos.Group;
using IM_API.Models;
using IM_API.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using Xunit;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MassTransit;
using IM_API.Configs;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace IM_API.Tests.Services
{
public class GroupServiceTests
{
private readonly ImContext _context;
private readonly IMapper _mapper;
private readonly Mock<ILogger<GroupService>> _loggerMock = new();
private readonly Mock<IPublishEndpoint> _publishMock = new();
public GroupServiceTests()
{
// 1. 配置内存数据库
var options = new DbContextOptionsBuilder<ImContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
_context = new ImContext(options);
// 2. 配置真实的 AutoMapper (ProjectTo 必须使用真实配置,不能用 Mock)
var config = new MapperConfiguration(cfg =>
{
// 替换为你项目中真实的 Profile 类名
cfg.AddProfile<MapperConfig>();
// 如果有多个 Profile可以继续添加或者加载整个程序集
// cfg.AddMaps(typeof(GroupProfile).Assembly);
});
_mapper = config.CreateMapper();
}
[Fact]
public async Task GetGroupList_ShouldReturnPagedAndOrderedData()
{
// Arrange (准备数据)
var userId = 1;
var groups = new List<Group>
{
new Group { Id = 101, Name = "Group A", Avatar = "1111" },
new Group { Id = 102, Name = "Group B" , Avatar = "1111"},
new Group { Id = 103, Name = "Group C", Avatar = "1111" }
};
_context.Groups.AddRange(groups);
_context.GroupMembers.AddRange(new List<GroupMember>
{
new GroupMember { UserId = userId, GroupId = 101 },
new GroupMember { UserId = userId, GroupId = 102 },
new GroupMember { UserId = userId, GroupId = 103 }
});
await _context.SaveChangesAsync();
var userService = new Mock<UserService>();
var service = new GroupService(_context, _mapper, _loggerMock.Object, _publishMock.Object,userService.Object);
// Act (执行测试: 第1页每页2条倒序)
var result = await service.GetGroupListAsync(userId, page: 1, limit: 2, desc: true);
// Assert (断言)
Assert.NotNull(result);
Assert.Equal(2, result.Count);
Assert.Equal(103, result[0].Id); // 倒序最大的是 103
Assert.Equal(102, result[1].Id);
}
[Fact]
public async Task GetGroupList_ShouldReturnEmpty_WhenUserHasNoGroups()
{
var userSerivce = new Mock<UserService>();
// Arrange
var service = new GroupService(_context, _mapper, _loggerMock.Object, _publishMock.Object, userSerivce.Object);
// Act
var result = await service.GetGroupListAsync(userId: 999, page: 1, limit: 10, desc: false);
// Assert
Assert.Empty(result);
}
}
}