Testing the sold-out process

It is possible to check the sold-out process by testing ItemSoldOutHandler. The handler will be tested with the same approach we saw for the other handlers:

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Cart.Domain.Events;
using Cart.Domain.Handlers.Cart;
using Cart.Fixtures;
using Shouldly;
using Xunit;

namespace Cart.Domain.Tests.Handlers.Events
{
public class ItemSoldOutEventHandlerTests : IClassFixture<CartContextFactory>
{
private readonly CartContextFactory _contextFactory;

public ItemSoldOutEventHandlerTests(CartContextFactory
cartContextFactory)
{
_contextFactory = cartContextFactory;
}

[Fact]
public async Task should_not_remove_records_whensoldout
message_contains_not_existing_id
()
{
var repository = _contextFactory.GetCartRepository();
var itemSoldOutEventHandler = new
ItemSoldOutEventHandler(repository);
var found = false;

await itemSoldOutEventHandler.Handle(new ItemSoldOutEvent {
Id = Guid.NewGuid().ToString() },
CancellationToken
.None);

var cartsIds = repository.GetCarts();

foreach (var cartId in cartsIds)
{
var cart = await repository.GetAsync(new Guid(cartId));
found = cart.Items.Any(i => i.CartItemId.ToString() ==
"be05537d-5e80-45c1-bd8c-
aa21c0f1251e"
);
}

found.ShouldBeTrue();
}

...
}
}

The ItemSoldOutEventHandlerTests class uses the CartContextFactory class to initialize a new repository in each test method using the _contextFactory.GetCartRepository(); method. Furthermore, the should_not_remove_records_when_soldout_message_contains_not_existing_id test method checks that nothing breaks if the ItemSoldOutEvent instance has a non-existent ID. On the other hand, the should_remove_records_when_soldout_messages_contains_existing_ids test method checks that ItemSoldOutEventHandler deletes the item in the basket when the ItemSoldOutEvent instance contains an existing ID:

...
[Fact]
public async Task should_remove_records_whensoldout
messages_contains_existing_ids()
{
var itemSoldOutId = "be05537d-5e80-45c1-bd8c-aa21c0f1251e";
var repository = _contextFactory.GetCartRepository();
var itemSoldOutEventHandler = new
ItemSoldOutEventHandler(repository);
var found = false;

await itemSoldOutEventHandler.Handle(new ItemSoldOutEvent {
Id = itemSoldOutId },
CancellationToken.None);

foreach (var cartId in repository.GetCarts())
{
var cart = await repository.GetAsync(new Guid(cartId));
found = cart.Items.Any(i => i.CartItemId.ToString() ==
itemSoldOutId);
}

found.ShouldBeFalse();
}
}
}

The second test method provides an existing item ID and verifies the handle method by checking whether the process has effectively removed the items. Now that we have verified the behavior of ItemSoldOutHandler, we can proceed by configuring and registering the event bus instance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.242.141