添加单元 测试

This commit is contained in:
2025-07-21 23:04:28 +08:00
parent 8f3543afb5
commit b881c89d96
9 changed files with 127 additions and 14 deletions

View File

@@ -12,6 +12,7 @@
<ItemGroup>
<PackageReference Include="Bogus" Version="35.6.3" />
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="JetBrains.Annotations" Version="2025.1.0-eap1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="xunit" Version="2.5.3" />

View File

@@ -0,0 +1,31 @@
using DMS.Core.Interfaces;
using DMS.Infrastructure.Configurations;
using DMS.Infrastructure.Data;
using DMS.Infrastructure.Services;
namespace DMS.Infrastructure.UnitTests.Services;
public class DatabaseServiceTest
{
private IDatabaseService _databaseService;
public DatabaseServiceTest()
{
AppSettings appSettings = new AppSettings();
appSettings.Database.Database = "dms_test";
SqlSugarDbContext dbContext=new SqlSugarDbContext(appSettings);
_databaseService = new DatabaseService(dbContext);
}
[Fact]
public void InitializeTables_Test()
{
_databaseService.InitializeTables();
Assert.True(_databaseService.IsAnyTable("dbdevice"));
}
[Fact]
public void InitializeTableIndex_Test()
{
_databaseService.InitializeTableIndex();
}
}

View File

@@ -0,0 +1,51 @@
using AutoMapper;
using DMS.Core.Models;
using DMS.Infrastructure.Configurations;
using DMS.Infrastructure.Data;
using DMS.Infrastructure.Profiles;
using DMS.Infrastructure.Repositories;
using DMS.Infrastructure.Services;
using JetBrains.Annotations;
namespace DMS.Infrastructure.UnitTests.Services;
[TestSubject(typeof(DeviceService))]
public class DeviceServiceTest
{
private readonly DeviceRepository _deviceRepository;
private readonly DeviceService _deviceService;
private readonly IMapper _mapper;
public DeviceServiceTest()
{
// 1. 创建 MapperConfiguration
var mappingConfig = new MapperConfiguration(mc =>
{
// 添加你的所有 Profile
mc.AddProfile(new MappingProfile());
// 如果有其他 Profile也可以在这里添加
// mc.AddProfile(new AnotherProfile());
});
// 2. 验证映射配置是否有效 (可选,但在开发环境中推荐)
mappingConfig.AssertConfigurationIsValid();
// 3. 创建 IMapper 实例
_mapper = mappingConfig.CreateMapper();
AppSettings appSettings = new AppSettings();
appSettings.Database.Database = "dms_test";
SqlSugarDbContext dbContext = new SqlSugarDbContext(appSettings);
_deviceRepository= new DeviceRepository(_mapper,dbContext);
_deviceService = new DeviceService(_deviceRepository);
}
[Fact]
public async Task AddAsync_Test()
{
var dbDevice = FakerHelper.FakeDbDevice();
var addDevice= await _deviceService.AddAsync(_mapper.Map<Device>(dbDevice));
Assert.NotEqual(0, addDevice.Id);
}
}