diff --git a/src/FIAP.TechChallenge.ByteMeBurger.Api/DomainEventsHandler.cs b/src/FIAP.TechChallenge.ByteMeBurger.Api/DomainEventsHandler.cs index b43d6b0..f6631bb 100644 --- a/src/FIAP.TechChallenge.ByteMeBurger.Api/DomainEventsHandler.cs +++ b/src/FIAP.TechChallenge.ByteMeBurger.Api/DomainEventsHandler.cs @@ -1,7 +1,5 @@ using System.Diagnostics.CodeAnalysis; using FIAP.TechChallenge.ByteMeBurger.Domain.Events; -using FIAP.TechChallenge.ByteMeBurger.Domain.Interfaces; -using FIAP.TechChallenge.ByteMeBurger.Domain.ValueObjects; using Microsoft.Extensions.Caching.Hybrid; namespace FIAP.TechChallenge.ByteMeBurger.Api; @@ -14,16 +12,11 @@ public class DomainEventsHandler : IDisposable { private readonly ILogger _logger; private readonly HybridCache _cache; - private readonly IOrderService _orderService; - public DomainEventsHandler(ILogger logger, HybridCache cache, IServiceProvider serviceProvider) + public DomainEventsHandler(ILogger logger, HybridCache cache) { _logger = logger; _cache = cache; - using (var scope = serviceProvider.CreateScope()) - { - _orderService = scope.ServiceProvider.GetRequiredService(); - } DomainEventTrigger.ProductCreated += OnProductCreated; DomainEventTrigger.ProductDeleted += OnProductDeleted; @@ -48,19 +41,10 @@ private void OnOrderStatusChanged(object? sender, OrderStatusChanged e) e.Payload.OldStatus, e.Payload.NewStatus, e.Payload.OrderId); } - private async void OnOrderPaymentConfirmed(object? sender, OrderPaymentConfirmed e) + private void OnOrderPaymentConfirmed(object? sender, OrderPaymentConfirmed e) { _logger.LogInformation("Order: {OrderId} payment confirmed", e.Payload); InvalidateOrderCache(e.Payload.OrderId); - try - { - await _orderService.UpdateStatusAsync(e.Payload.OrderId, OrderStatus.Received); - } - catch (Exception exception) - { - _logger.LogError(exception, "Error updating order status {OrderId}", e.Payload.OrderId); - throw; - } } private void OnOrderCreated(object? sender, OrderCreated e) @@ -85,20 +69,10 @@ private void OnProductCreated(object? sender, ProductCreated e) _logger.LogInformation("Product created: {@Product}", e.Payload); } - private async void OnPaymentCreated(object? sender, PaymentCreated e) + private void OnPaymentCreated(object? sender, PaymentCreated e) { _logger.LogInformation("Payment {PaymentId} created for Order: {OrderId}", e.Payload.OrderId, e.Payload.Id.Value); - - try - { - await _orderService.UpdateOrderPaymentAsync(e.Payload.OrderId, e.Payload.Id); - } - catch (Exception exception) - { - _logger.LogError(exception, "Error updating order payment {OrderId}", e.Payload.OrderId); - throw; - } } private void InvalidateOrderCache(Guid orderId) diff --git a/src/FIAP.TechChallenge.ByteMeBurger.Api/appsettings.Development.json b/src/FIAP.TechChallenge.ByteMeBurger.Api/appsettings.Development.json index ea5a648..a096eb8 100644 --- a/src/FIAP.TechChallenge.ByteMeBurger.Api/appsettings.Development.json +++ b/src/FIAP.TechChallenge.ByteMeBurger.Api/appsettings.Development.json @@ -16,9 +16,9 @@ "MySql": "Server=localhost;Database=restaurant1;Uid=italo;Pwd=italo123@;Port=3306" }, "MercadoPago": { - "WebhookSecret": "", - "AccessToken": "", - "NotificationUrl": "" + "WebhookSecret": "1232", + "AccessToken": "123", + "NotificationUrl": "1232" }, "HybridCache": { "Expiration": "01:00:00", diff --git a/src/FIAP.TechChallenge.ByteMeBurger.Application/Controllers/PaymentService.cs b/src/FIAP.TechChallenge.ByteMeBurger.Application/Controllers/PaymentService.cs index 5e2628c..11aa5bf 100644 --- a/src/FIAP.TechChallenge.ByteMeBurger.Application/Controllers/PaymentService.cs +++ b/src/FIAP.TechChallenge.ByteMeBurger.Application/Controllers/PaymentService.cs @@ -12,16 +12,19 @@ public class PaymentService : IPaymentService private readonly IUpdatePaymentStatusUseCase _updatePaymentStatusUseCase; private readonly IPaymentRepository _paymentRepository; private readonly IPaymentGatewayFactoryMethod _paymentGatewayFactory; + private readonly IUpdateOrderPaymentUseCase _updateOrderPaymentUseCase; public PaymentService(ICreatePaymentUseCase createOrderPaymentUseCase, IUpdatePaymentStatusUseCase updatePaymentStatusUseCase, IPaymentRepository paymentRepository, - IPaymentGatewayFactoryMethod paymentGatewayFactory) + IPaymentGatewayFactoryMethod paymentGatewayFactory, + IUpdateOrderPaymentUseCase updateOrderPaymentUseCase) { _createOrderPaymentUseCase = createOrderPaymentUseCase; _updatePaymentStatusUseCase = updatePaymentStatusUseCase; _paymentRepository = paymentRepository; _paymentGatewayFactory = paymentGatewayFactory; + _updateOrderPaymentUseCase = updateOrderPaymentUseCase; } public async Task CreateOrderPaymentAsync(CreateOrderPaymentRequestDto command) @@ -31,6 +34,7 @@ public async Task CreateOrderPaymentAsync(CreateOrderPaymentRequestDto return null; await _paymentRepository.SaveAsync(payment); + await _updateOrderPaymentUseCase.Execute(payment.OrderId, payment.Id); return payment; } diff --git a/src/FIAP.TechChallenge.ByteMeBurger.Application/UseCases/Payment/UpdatePaymentStatusUseCase.cs b/src/FIAP.TechChallenge.ByteMeBurger.Application/UseCases/Payment/UpdatePaymentStatusUseCase.cs index cb44b0f..2c9c74c 100644 --- a/src/FIAP.TechChallenge.ByteMeBurger.Application/UseCases/Payment/UpdatePaymentStatusUseCase.cs +++ b/src/FIAP.TechChallenge.ByteMeBurger.Application/UseCases/Payment/UpdatePaymentStatusUseCase.cs @@ -1,3 +1,4 @@ +using FIAP.TechChallenge.ByteMeBurger.Application.UseCases.Orders; using FIAP.TechChallenge.ByteMeBurger.Domain.Events; using FIAP.TechChallenge.ByteMeBurger.Domain.Interfaces; using FIAP.TechChallenge.ByteMeBurger.Domain.ValueObjects; @@ -7,10 +8,13 @@ namespace FIAP.TechChallenge.ByteMeBurger.Application.UseCases.Payment; public class UpdatePaymentStatusUseCase : IUpdatePaymentStatusUseCase { private readonly IPaymentRepository _paymentRepository; + private readonly IUpdateOrderStatusUseCase _updateOrderStatusUseCase; - public UpdatePaymentStatusUseCase(IPaymentRepository paymentRepository) + public UpdatePaymentStatusUseCase(IUpdateOrderStatusUseCase updateOrderStatusUseCase, + IPaymentRepository paymentRepository) { _paymentRepository = paymentRepository; + _updateOrderStatusUseCase = updateOrderStatusUseCase; } public async Task Execute(Domain.Entities.Payment? payment, PaymentStatus status) @@ -28,6 +32,8 @@ and not PaymentStatus.Cancelled if (paymentStatusUpdated && payment.IsApproved()) { DomainEventTrigger.RaisePaymentConfirmed(payment); + // TODO change to eventual consistency. use events to update order status + await _updateOrderStatusUseCase.Execute(payment.OrderId, OrderStatus.Received); } return paymentStatusUpdated; diff --git a/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/CustomerRepositoryDapper.cs b/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/CustomerRepositoryDapper.cs index 0d10e41..15171b3 100644 --- a/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/CustomerRepositoryDapper.cs +++ b/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/CustomerRepositoryDapper.cs @@ -1,6 +1,5 @@ using System.Data; using Dapper; -using FIAP.TechChallenge.ByteMeBurger.Domain.Base; using FIAP.TechChallenge.ByteMeBurger.Domain.Entities; using FIAP.TechChallenge.ByteMeBurger.Domain.Interfaces; using FIAP.TechChallenge.ByteMeBurger.Persistence.Dto; @@ -8,16 +7,14 @@ namespace FIAP.TechChallenge.ByteMeBurger.Persistence.Repository; -public class CustomerRepositoryDapper(IDbContext context, ILogger logger) +public class CustomerRepositoryDapper(IDbConnection dbConnection, ILogger logger) : ICustomerRepository { - private readonly IDbConnection _dbConnection = context.CreateConnection(); - public async Task FindByCpfAsync(string cpf) { logger.LogInformation("Finding customer by CPF: {Cpf}", cpf); - var customerDto = await _dbConnection.QuerySingleOrDefaultAsync( + var customerDto = await dbConnection.QuerySingleOrDefaultAsync( Constants.GetCustomerByCpfQuery, new { Cpf = cpf }); @@ -33,7 +30,7 @@ public async Task CreateAsync(Customer customer) { logger.LogInformation("Creating customer with CPF: {Cpf}", customer.Cpf); var param = (CustomerDto)customer; - var rowsAffected = await _dbConnection.ExecuteAsync( + var rowsAffected = await dbConnection.ExecuteAsync( Constants.InsertCustomerQuery, param); diff --git a/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/OrderRepositoryDapper.cs b/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/OrderRepositoryDapper.cs index dcc50d3..50fc5ce 100644 --- a/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/OrderRepositoryDapper.cs +++ b/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/OrderRepositoryDapper.cs @@ -11,20 +11,18 @@ namespace FIAP.TechChallenge.ByteMeBurger.Persistence.Repository; -public class OrderRepositoryDapper(IDbContext context, ILogger logger) +public class OrderRepositoryDapper(IDbConnection dbConnection, ILogger logger) : IOrderRepository { - private readonly IDbConnection _dbConnection = context.CreateConnection(); - public async Task CreateAsync(Order order) { logger.LogInformation("Persisting order {OrderId}", order.Id); - var transaction = _dbConnection.BeginTransaction(); + var transaction = dbConnection.BeginTransaction(); { try { - await _dbConnection.ExecuteAsync( + await dbConnection.ExecuteAsync( Constants.InsertOrderQuery, new { @@ -34,7 +32,7 @@ await _dbConnection.ExecuteAsync( order.Created, TrackingCode = order.TrackingCode.Value }); - await _dbConnection.ExecuteAsync(Constants.InsertOrderItemsQuery, order.OrderItems); + await dbConnection.ExecuteAsync(Constants.InsertOrderItemsQuery, order.OrderItems); transaction.Commit(); logger.LogInformation("Order {OrderId} persisted", order.Id); @@ -55,7 +53,7 @@ public async Task> GetAllAsync() var ordersDictionary = new Dictionary(); - await _dbConnection.QueryAsync( + await dbConnection.QueryAsync( Constants.GetAllOrdersQuery, (orderListDto, customerDto, paymentDao, orderItemDto) => { @@ -94,7 +92,7 @@ public async Task> GetAllAsync() logger.LogInformation("Getting order {OrderId} from database", orderId); var ordersDictionary = new Dictionary(); - await _dbConnection.QueryAsync( + await dbConnection.QueryAsync( Constants.GetOrderByIdQuery, (orderListDto, paymentId, customerDto, orderItemDto) => { @@ -132,7 +130,7 @@ public async Task UpdateOrderStatusAsync(Order order) logger.LogInformation("Updating order {OrderId} status to {OrderStatus}", order.Id, order.Status); try { - var updated = await _dbConnection.ExecuteAsync( + var updated = await dbConnection.ExecuteAsync( Constants.UpdateOrderStatusQuery, new { @@ -159,7 +157,7 @@ public async Task UpdateOrderPaymentAsync(Order order) logger.LogInformation("Updating order {OrderId} Payment {PaymentId}", order.Id, order.PaymentId.Value); try { - var updated = await _dbConnection.ExecuteAsync( + var updated = await dbConnection.ExecuteAsync( Constants.UpdateOrderPaymentIdQuery, new { diff --git a/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/PaymentRepositoryDapper.cs b/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/PaymentRepositoryDapper.cs index 7893504..dc7cd00 100644 --- a/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/PaymentRepositoryDapper.cs +++ b/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/PaymentRepositoryDapper.cs @@ -10,24 +10,23 @@ namespace FIAP.TechChallenge.ByteMeBurger.Persistence.Repository; public class PaymentRepositoryDapper( - IDbContext context, + IDbConnection dbConnection, ILogger logger) : IPaymentRepository { - private readonly IDbConnection _dbConnection = context.CreateConnection(); public async Task SaveAsync(Payment payment) { logger.LogInformation("Persisting Payment {PaymentId} for Order {OrderId}", payment.Id.Value, payment.OrderId); - var transaction = _dbConnection.BeginTransaction(); + var transaction = dbConnection.BeginTransaction(); { try { var paymentDao = new PaymentDto(payment.Id.Value, payment.OrderId, (int)payment.Status, (int)payment.PaymentType, payment.Amount, payment.ExternalReference, payment.Created, null); - await _dbConnection.ExecuteAsync(Constants.InsertPaymentQuery, paymentDao); + await dbConnection.ExecuteAsync(Constants.InsertPaymentQuery, paymentDao); transaction.Commit(); @@ -48,7 +47,7 @@ public async Task SaveAsync(Payment payment) { logger.LogInformation("Getting Payment {PaymentId}", paymentId.Value); - var paymentDao = await _dbConnection.QuerySingleOrDefaultAsync( + var paymentDao = await dbConnection.QuerySingleOrDefaultAsync( Constants.GetPaymentQuery, param: new { Id = paymentId.Value } ); @@ -76,7 +75,7 @@ public async Task SaveAsync(Payment payment) logger.LogInformation("Getting {PaymentType} Payment by ExternalReference {ExternalReference}", paymentType.ToString(), externalReference); - var paymentDao = await _dbConnection.QuerySingleOrDefaultAsync( + var paymentDao = await dbConnection.QuerySingleOrDefaultAsync( Constants.GetPaymentByExternalReferenceQuery, param: new { @@ -108,7 +107,7 @@ public async Task UpdatePaymentStatusAsync(Payment payment) { logger.LogInformation("Updating Payment {PaymentId} status", payment.Id.Value); - var updated = await _dbConnection.ExecuteAsync( + var updated = await dbConnection.ExecuteAsync( Constants.UpdatePaymentStatusQuery, new { diff --git a/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/ProductRepositoryDapper.cs b/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/ProductRepositoryDapper.cs index 0203a97..31718fe 100644 --- a/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/ProductRepositoryDapper.cs +++ b/src/FIAP.TechChallenge.ByteMeBurger.Persistence/Repository/ProductRepositoryDapper.cs @@ -11,15 +11,14 @@ namespace FIAP.TechChallenge.ByteMeBurger.Persistence.Repository; -public class ProductRepositoryDapper(IDbContext context, ILogger logger) +public class ProductRepositoryDapper(IDbConnection dbConnection, ILogger logger) : IProductRepository { - private readonly IDbConnection _dbConnection = context.CreateConnection(); public async Task FindByIdAsync(Guid id) { logger.LogInformation("Finding product {ProductId}", id); - var productDto = await _dbConnection.QuerySingleOrDefaultAsync( + var productDto = await dbConnection.QuerySingleOrDefaultAsync( "SELECT * FROM Products WHERE Id=@Id", param: new { Id = id }); @@ -35,7 +34,7 @@ public async Task CreateAsync(Product product) { logger.LogInformation("Creating product with name: {ProductName}", product.Name); var param = (ProductDto)product; - var affectedRows = await _dbConnection.ExecuteAsync(Constants.InsertProductQuery, param); + var affectedRows = await dbConnection.ExecuteAsync(Constants.InsertProductQuery, param); if (affectedRows > 0) { @@ -52,7 +51,7 @@ public async Task CreateAsync(Product product) public async Task DeleteAsync(Guid productId) { logger.LogInformation("Deleting product {ProductId}", productId); - var affectedRows = await _dbConnection.ExecuteAsync(Constants.DeleteProductQuery, + var affectedRows = await dbConnection.ExecuteAsync(Constants.DeleteProductQuery, new { Id = productId }); if (affectedRows == 1) @@ -70,7 +69,7 @@ public async Task DeleteAsync(Guid productId) public async Task> GetAll() { logger.LogInformation("Getting all products"); - var productDtoList = await _dbConnection.QueryAsync( + var productDtoList = await dbConnection.QueryAsync( "SELECT * FROM Products"); logger.LogInformation("Retrieved {Count} products", productDtoList.Count()); @@ -82,7 +81,7 @@ public async Task> GetAll() public async Task> FindByCategory(ProductCategory category) { logger.LogInformation("Finding products by category: {ProductCategory}", category); - var productDtoList = await _dbConnection.QueryAsync( + var productDtoList = await dbConnection.QueryAsync( "SELECT * FROM Products WHERE Category = @Category", param: new { Category = (int)category }); @@ -93,7 +92,7 @@ public async Task> FindByCategory(ProductCategory ca public async Task UpdateAsync(Product product) { logger.LogInformation("Updating product with ID: {ProductId}", product.Id); - var affectedRows = await _dbConnection.ExecuteAsync( + var affectedRows = await dbConnection.ExecuteAsync( Constants.UpdateProductQuery, (ProductDto)product); diff --git a/src/FIAP.TechChallenge.ByteMeBurger.Persistence/ServiceExtensions.cs b/src/FIAP.TechChallenge.ByteMeBurger.Persistence/ServiceExtensions.cs index c32d2ed..0bbf88b 100644 --- a/src/FIAP.TechChallenge.ByteMeBurger.Persistence/ServiceExtensions.cs +++ b/src/FIAP.TechChallenge.ByteMeBurger.Persistence/ServiceExtensions.cs @@ -1,7 +1,6 @@ using System.Data; using System.Data.Common; using System.Diagnostics.CodeAnalysis; -using FIAP.TechChallenge.ByteMeBurger.Domain.Base; using FIAP.TechChallenge.ByteMeBurger.Domain.Interfaces; using FIAP.TechChallenge.ByteMeBurger.Persistence.Repository; using Microsoft.Extensions.Configuration; @@ -15,16 +14,15 @@ public static class ServiceExtensions { public static void ConfigurePersistenceApp(this IServiceCollection services, IConfiguration configuration) { - services.AddSingleton(); - // services.AddScoped(_ => - // { - // DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient", MySqlClientFactory.Instance); - // var providerFactory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient"); - // var conn = providerFactory.CreateConnection(); - // conn.ConnectionString = configuration.GetConnectionString("MySql"); - // // conn.Open(); - // return conn; - // }); + services.AddScoped(_ => + { + DbProviderFactories.RegisterFactory("MySql.Data.MySqlClient", MySqlClientFactory.Instance); + var providerFactory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient"); + var conn = providerFactory.CreateConnection(); + conn.ConnectionString = configuration.GetConnectionString("MySql"); + conn.Open(); + return conn; + }); services.AddScoped() .AddScoped() diff --git a/tests/FIAP.TechChallenge.ByteMeBurger.Application.Test/Services/PaymentServiceTests.cs b/tests/FIAP.TechChallenge.ByteMeBurger.Application.Test/Services/PaymentServiceTests.cs index 48072ec..f310011 100644 --- a/tests/FIAP.TechChallenge.ByteMeBurger.Application.Test/Services/PaymentServiceTests.cs +++ b/tests/FIAP.TechChallenge.ByteMeBurger.Application.Test/Services/PaymentServiceTests.cs @@ -1,5 +1,6 @@ using AutoFixture; using FIAP.TechChallenge.ByteMeBurger.Application.Controllers; +using FIAP.TechChallenge.ByteMeBurger.Application.UseCases.Orders; using FIAP.TechChallenge.ByteMeBurger.Application.UseCases.Payment; using FIAP.TechChallenge.ByteMeBurger.Domain.Interfaces; @@ -13,6 +14,7 @@ public class PaymentServiceTests private readonly Mock _mockUpdatePaymentStatusUseCase; private readonly Mock _mockPaymentGateway; private readonly PaymentService _target; + private readonly Mock _mockUpdateOrderPaymentUseCase; public PaymentServiceTests() { @@ -20,13 +22,14 @@ public PaymentServiceTests() _mockPaymentRepository = new Mock(); _mockUpdatePaymentStatusUseCase = new Mock(); _mockPaymentGateway = new Mock(); + _mockUpdateOrderPaymentUseCase = new Mock(); Mock paymentGatewayFactory = new(); paymentGatewayFactory.Setup(g => g.Create(It.IsAny())) .Returns(_mockPaymentGateway.Object); _target = new PaymentService(_mockCreatePaymentUseCase.Object, _mockUpdatePaymentStatusUseCase.Object, - _mockPaymentRepository.Object, paymentGatewayFactory.Object); + _mockPaymentRepository.Object, paymentGatewayFactory.Object, _mockUpdateOrderPaymentUseCase.Object); } [Fact] diff --git a/tests/FIAP.TechChallenge.ByteMeBurger.Application.Test/UseCases/Payment/UpdatePaymentStatusUseCaseTest.cs b/tests/FIAP.TechChallenge.ByteMeBurger.Application.Test/UseCases/Payment/UpdatePaymentStatusUseCaseTest.cs index fee0621..d19e12c 100644 --- a/tests/FIAP.TechChallenge.ByteMeBurger.Application.Test/UseCases/Payment/UpdatePaymentStatusUseCaseTest.cs +++ b/tests/FIAP.TechChallenge.ByteMeBurger.Application.Test/UseCases/Payment/UpdatePaymentStatusUseCaseTest.cs @@ -1,4 +1,5 @@ using AutoFixture; +using FIAP.TechChallenge.ByteMeBurger.Application.UseCases.Orders; using FIAP.TechChallenge.ByteMeBurger.Application.UseCases.Payment; using FIAP.TechChallenge.ByteMeBurger.Domain.Interfaces; @@ -7,13 +8,15 @@ namespace FIAP.TechChallenge.ByteMeBurger.Application.Test.UseCases.Payment; [TestSubject(typeof(UpdatePaymentStatusUseCase))] public class UpdatePaymentStatusUseCaseTest { + private readonly Mock _mockUpdateOrderStatusUseCase; private readonly Mock _mockPaymentRepository; private readonly UpdatePaymentStatusUseCase _target; public UpdatePaymentStatusUseCaseTest() { + _mockUpdateOrderStatusUseCase = new Mock(); _mockPaymentRepository = new Mock(); - _target = new UpdatePaymentStatusUseCase(_mockPaymentRepository.Object); + _target = new UpdatePaymentStatusUseCase(_mockUpdateOrderStatusUseCase.Object, _mockPaymentRepository.Object); } [Fact] @@ -35,6 +38,7 @@ public async void Execute_UpdatePaymentAndOrderStatus_Success() using (new AssertionScope()) { result.Should().BeTrue(); + _mockUpdateOrderStatusUseCase.Verify(); } } } diff --git a/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/CustomerRepositoryDapperTest.cs b/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/CustomerRepositoryDapperTest.cs index 51f1d0e..fc894e6 100644 --- a/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/CustomerRepositoryDapperTest.cs +++ b/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/CustomerRepositoryDapperTest.cs @@ -16,18 +16,14 @@ namespace FIAP.TechChallenge.ByteMeBurger.Persistence.Test.Repository; [TestSubject(typeof(CustomerRepositoryDapper))] public class CustomerRepositoryDapperTest { - private readonly Mock _mockDbConnection; + private readonly Mock _mockConnection; private readonly CustomerRepositoryDapper _target; private const string Cpf = "20697137090"; public CustomerRepositoryDapperTest() { - Mock mockDbContext = new(); - _mockDbConnection = new Mock(); - _mockDbConnection.Setup(c => c.BeginTransaction()).Returns(Mock.Of()); - mockDbContext.Setup(s => s.CreateConnection()) - .Returns(_mockDbConnection.Object); - _target = new CustomerRepositoryDapper(mockDbContext.Object, Mock.Of>()); + _mockConnection = new Mock(); + _target = new CustomerRepositoryDapper(_mockConnection.Object,Mock.Of>()); } [Fact] @@ -36,7 +32,8 @@ public async Task Create_Success() // Arrange var customer = new Customer(Cpf); - _mockDbConnection.SetupDapperAsync(c => + _mockConnection.Setup(c => c.BeginTransaction()).Returns(Mock.Of()); + _mockConnection.SetupDapperAsync(c => c.ExecuteAsync("", null, null, null, null)) .ReturnsAsync(1); @@ -63,7 +60,7 @@ public async Task FindByCpf_Success() Email = "italo@gmail.com" }; - _mockDbConnection.SetupDapperAsync(c => + _mockConnection.SetupDapperAsync(c => c.QuerySingleOrDefaultAsync(It.IsAny(), null, null, null, null)) .ReturnsAsync(expectedCustomer); @@ -84,7 +81,7 @@ public async Task FindByCpf_Success() public async Task FindByCpf_NotFound() { // Arrange - _mockDbConnection.SetupDapperAsync(c => + _mockConnection.SetupDapperAsync(c => c.QuerySingleOrDefaultAsync(It.IsAny(), null, null, null, null)) .ReturnsAsync(default(Customer)); diff --git a/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/OrderRepositoryDapperTest.cs b/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/OrderRepositoryDapperTest.cs index 3b9217c..2e151ea 100644 --- a/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/OrderRepositoryDapperTest.cs +++ b/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/OrderRepositoryDapperTest.cs @@ -22,13 +22,8 @@ public class OrderRepositoryDapperTest public OrderRepositoryDapperTest() { - Mock mockDbContext = new(); _mockConnection = new Mock(); - _mockConnection.Setup(c => c.BeginTransaction()).Returns(Mock.Of()); - mockDbContext.Setup(s => s.CreateConnection()) - .Returns(_mockConnection.Object); - - _target = new OrderRepositoryDapper(mockDbContext.Object, Mock.Of>()); + _target = new OrderRepositoryDapper(_mockConnection.Object, Mock.Of>()); } [Fact(Skip = "I'll double check it later")] @@ -69,6 +64,7 @@ public async Task Create_Success() order.AddOrderItem(Guid.NewGuid(), "banana", 10, 1); order.SetTrackingCode(new OrderTrackingCode("code")); + _mockConnection.Setup(c => c.BeginTransaction()).Returns(Mock.Of()); _mockConnection.SetupDapperAsync(c => c.ExecuteAsync( "insert into Orders (Id, CustomerId, Status, Created, TrackingCode) values (@Id, @CustomerId, @Status, @Created, @TrackingCode);", diff --git a/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/PaymentRepositoryDapperTest.cs b/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/PaymentRepositoryDapperTest.cs index 19b9f2b..f9185ec 100644 --- a/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/PaymentRepositoryDapperTest.cs +++ b/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/PaymentRepositoryDapperTest.cs @@ -23,12 +23,8 @@ public class PaymentRepositoryDapperTest public PaymentRepositoryDapperTest() { - Mock mockDbContext = new(); _mockConnection = new Mock(); - _mockConnection.Setup(c => c.BeginTransaction()).Returns(Mock.Of()); - mockDbContext.Setup(s => s.CreateConnection()) - .Returns(_mockConnection.Object); - _target = new PaymentRepositoryDapper(mockDbContext.Object, Mock.Of>()); + _target = new PaymentRepositoryDapper(_mockConnection.Object, Mock.Of>()); } [Fact] @@ -37,6 +33,8 @@ public async Task Create_Success() // Arrange var expectedPayment = new Fixture().Create(); + _mockConnection.Setup(c => c.BeginTransaction()).Returns(Mock.Of()); + _mockConnection.SetupDapperAsync(c => c.ExecuteAsync(Constants.InsertPaymentQuery, null, null, null, null)) diff --git a/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/ProductRepositoryDapperTest.cs b/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/ProductRepositoryDapperTest.cs index 2590442..6022c6e 100644 --- a/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/ProductRepositoryDapperTest.cs +++ b/tests/FIAP.TechChallenge.ByteMeBurger.Persistence.Test/Repository/ProductRepositoryDapperTest.cs @@ -17,17 +17,13 @@ namespace FIAP.TechChallenge.ByteMeBurger.Persistence.Test.Repository; [TestSubject(typeof(ProductRepositoryDapper))] public class ProductRepositoryDapperTest { - private readonly Mock _mockDbConnection; + private readonly Mock _mockConnection; private readonly ProductRepositoryDapper _target; public ProductRepositoryDapperTest() { - Mock mockDbContext = new(); - _mockDbConnection = new Mock(); - _mockDbConnection.Setup(c => c.BeginTransaction()).Returns(Mock.Of()); - mockDbContext.Setup(s => s.CreateConnection()) - .Returns(_mockDbConnection.Object); - _target = new ProductRepositoryDapper(mockDbContext.Object, Mock.Of>()); + _mockConnection = new Mock(); + _target = new ProductRepositoryDapper(_mockConnection.Object, Mock.Of>()); } [Fact] @@ -40,7 +36,7 @@ public async Task Create_Success() const string sql = "INSERT INTO Products (Name, Description, Category, Price, Images) VALUES (@Name, @Description, @Category, @Price, @Images)"; - _mockDbConnection.SetupDapperAsync(c => c.ExecuteAsync(sql, parameters, null, null, null)) + _mockConnection.SetupDapperAsync(c => c.ExecuteAsync(sql, parameters, null, null, null)) .ReturnsAsync(1); // Act @@ -51,7 +47,7 @@ public async Task Create_Success() { result.Should().NotBeNull(); result.Should().BeEquivalentTo(product, options => options.ComparingByMembers()); - _mockDbConnection.Verify(); + _mockConnection.Verify(); } } @@ -60,7 +56,7 @@ public async Task DeleteAsync_Success() { // Arrange var productId = Guid.NewGuid(); - _mockDbConnection + _mockConnection .SetupDapperAsync(db => db.ExecuteAsync(It.IsAny(), It.IsAny(), null, null, null)) .ReturnsAsync(1); @@ -76,7 +72,7 @@ public async Task DeleteAsync_Fail() { // Arrange var productId = Guid.NewGuid(); - _mockDbConnection + _mockConnection .SetupDapperAsync(db => db.ExecuteAsync(It.IsAny(), It.IsAny(), null, null, null)) .ReturnsAsync(0); @@ -102,7 +98,7 @@ public async Task FindByIdAsync_Success() CreationDate = DateTime.UtcNow }; - _mockDbConnection.SetupDapperAsync(c => c.QueryAsync(It.IsAny(), null, null, null, null)) + _mockConnection.SetupDapperAsync(c => c.QueryAsync(It.IsAny(), null, null, null, null)) .ReturnsAsync([product]); // Act @@ -137,7 +133,7 @@ public async Task FindByCategoryAsync_Success() Images = "image1|image 2" }; - _mockDbConnection.SetupDapperAsync(c => c.QueryAsync(It.IsAny(), null, null, null, null)) + _mockConnection.SetupDapperAsync(c => c.QueryAsync(It.IsAny(), null, null, null, null)) .ReturnsAsync([product]); // Act @@ -177,7 +173,7 @@ public async Task Update_Success() Images = string.Join("|", product.Images) }; - _mockDbConnection.SetupDapperAsync(c => c.ExecuteAsync(sql, parameters, null, null, null)) + _mockConnection.SetupDapperAsync(c => c.ExecuteAsync(sql, parameters, null, null, null)) .ReturnsAsync(1); // Act @@ -187,7 +183,7 @@ public async Task Update_Success() using (new AssertionScope()) { result.Should().BeTrue(); - _mockDbConnection.Verify(); + _mockConnection.Verify(); } } }