91 lines
3.2 KiB
C#
91 lines
3.2 KiB
C#
using EndavaTask.Contracts;
|
|
using EndavaTask.Data;
|
|
using EndavaTask.Dtos;
|
|
using EndavaTask.Exceptions;
|
|
using EndavaTask.Models;
|
|
using EndavaTask.Services;
|
|
using Moq;
|
|
using Xunit;
|
|
|
|
namespace EndavaTask.Tests;
|
|
|
|
public class ProductServiceTests
|
|
{
|
|
[Fact]
|
|
public void GetProducts_WithRepositoryResult_MapsAndReturnsPagedResult()
|
|
{
|
|
var categoryId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
|
|
var repositoryMock = new Mock<IProductRepository>();
|
|
|
|
repositoryMock
|
|
.Setup(r => r.CategoryExists(categoryId))
|
|
.Returns(true);
|
|
|
|
repositoryMock
|
|
.Setup(r => r.GetFilteredProducts(It.IsAny<ProductFilterQuery>(), It.IsAny<PaginationQuery>()))
|
|
.Returns(new PagedResult<Product>
|
|
{
|
|
Items =
|
|
[
|
|
new Product { Id = Guid.NewGuid(), Name = "Laptop", Price = 1200m, CategoryId = categoryId },
|
|
new Product { Id = Guid.NewGuid(), Name = "Headphones", Price = 180m, CategoryId = categoryId }
|
|
],
|
|
PageNumber = 1,
|
|
PageSize = 2,
|
|
TotalCount = 3,
|
|
TotalPages = 2
|
|
});
|
|
|
|
var service = new ProductService(repositoryMock.Object);
|
|
var result = service.GetProducts(new ProductFilterQuery { CategoryId = categoryId }, new PaginationQuery { PageNumber = 1, PageSize = 2 });
|
|
var value = Assert.IsType<PagedResult<ProductDto>>(result);
|
|
|
|
Assert.Equal(2, value.Items.Count);
|
|
Assert.Equal(3, value.TotalCount);
|
|
Assert.Equal(2, value.TotalPages);
|
|
}
|
|
|
|
[Fact]
|
|
public void UpdateProduct_WithRepositoryEntity_ReturnsMappedDto()
|
|
{
|
|
var productId = Guid.Parse("55555555-5555-5555-5555-555555555555");
|
|
var categoryId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
|
|
|
|
var repositoryMock = new Mock<IProductRepository>();
|
|
|
|
repositoryMock
|
|
.Setup(r => r.UpdateProduct(productId, It.IsAny<UpdateProductRequest>()))
|
|
.Returns(new Product
|
|
{
|
|
Id = productId,
|
|
Name = "Updated Monitor",
|
|
Price = 350m,
|
|
CategoryId = categoryId
|
|
});
|
|
|
|
var service = new ProductService(repositoryMock.Object);
|
|
var result = service.UpdateProduct(productId, new UpdateProductRequest { Name = "Updated Monitor", Price = 350m });
|
|
var value = Assert.IsType<ProductDto>(result);
|
|
|
|
Assert.Equal("Updated Monitor", value.Name);
|
|
Assert.Equal(350m, value.Price);
|
|
}
|
|
|
|
[Fact]
|
|
public void GetProducts_WithUnknownCategory_ThrowsValidationException()
|
|
{
|
|
var repositoryMock = new Mock<IProductRepository>();
|
|
|
|
repositoryMock
|
|
.Setup(r => r.CategoryExists(It.IsAny<Guid>()))
|
|
.Returns(false);
|
|
|
|
var service = new ProductService(repositoryMock.Object);
|
|
|
|
var exception = Assert.Throws<ApiValidationException>(() =>
|
|
service.GetProducts(new ProductFilterQuery { CategoryId = Guid.NewGuid() }, new PaginationQuery()));
|
|
|
|
Assert.True(exception.Errors.ContainsKey(nameof(ProductFilterQuery.CategoryId)));
|
|
}
|
|
}
|