Files
it/HardwarePerformance.Tests/Services/CategoryServiceTests.cs
2025-11-03 17:03:57 +08:00

97 lines
3.6 KiB
C#

using AutoMapper;
using HardwarePerformance.Models;
using HardwarePerformance.Models.DTOs;
using HardwarePerformance.Services;
using Moq;
namespace HardwarePerformance.Tests.Services
{
public class CategoryServiceTests
{
private readonly Mock<ICategoryRepository> _mockCategoryRepository;
private readonly Mock<IMapper> _mockMapper;
private readonly CategoryService _categoryService;
public CategoryServiceTests()
{
_mockCategoryRepository = new Mock<ICategoryRepository>();
_mockMapper = new Mock<IMapper>();
_categoryService = new CategoryService(_mockCategoryRepository.Object, _mockMapper.Object);
}
[Fact]
public async Task GetAllCategoriesAsync_ReturnsAllCategories()
{
// Arrange
var categories = new List<Category>
{
new Category { Id = 1, Name = "手机CPU", Description = "手机处理器" },
new Category { Id = 2, Name = "电脑CPU", Description = "电脑处理器" }
};
var categoryDtos = new List<CategoryDto>
{
new CategoryDto { Id = 1, Name = "手机CPU", Description = "手机处理器" },
new CategoryDto { Id = 2, Name = "电脑CPU", Description = "电脑处理器" }
};
_mockCategoryRepository.Setup(repo => repo.GetAllAsync())
.ReturnsAsync(categories);
_mockMapper.Setup(m => m.Map<IEnumerable<CategoryDto>>(categories))
.Returns(categoryDtos);
// Act
var result = await _categoryService.GetAllCategoriesAsync();
// Assert
Assert.NotNull(result);
Assert.Equal(2, result.Count());
_mockCategoryRepository.Verify(repo => repo.GetAllAsync(), Times.Once);
_mockMapper.Verify(m => m.Map<IEnumerable<CategoryDto>>(categories), Times.Once);
}
[Fact]
public async Task GetCategoryByIdAsync_ExistingCategory_ReturnsCategoryDto()
{
// Arrange
var categoryId = 1;
var category = new Category { Id = categoryId, Name = "手机CPU", Description = "手机处理器" };
var categoryDto = new CategoryDto { Id = categoryId, Name = "手机CPU", Description = "手机处理器" };
_mockCategoryRepository.Setup(repo => repo.GetByIdAsync(categoryId))
.ReturnsAsync(category);
_mockMapper.Setup(m => m.Map<CategoryDto>(category))
.Returns(categoryDto);
// Act
var result = await _categoryService.GetCategoryByIdAsync(categoryId);
// Assert
Assert.NotNull(result);
Assert.Equal(categoryId, result.Id);
Assert.Equal("手机CPU", result.Name);
_mockCategoryRepository.Verify(repo => repo.GetByIdAsync(categoryId), Times.Once);
_mockMapper.Verify(m => m.Map<CategoryDto>(category), Times.Once);
}
[Fact]
public async Task GetCategoryByIdAsync_NonExistingCategory_ReturnsNull()
{
// Arrange
var categoryId = 999;
_mockCategoryRepository.Setup(repo => repo.GetByIdAsync(categoryId))
.ReturnsAsync((Category?)null);
// Act
var result = await _categoryService.GetCategoryByIdAsync(categoryId);
// Assert
Assert.Null(result);
_mockCategoryRepository.Verify(repo => repo.GetByIdAsync(categoryId), Times.Once);
_mockMapper.Verify(m => m.Map<CategoryDto>(It.IsAny<Category>()), Times.Never);
}
}
}