Test: Buy 2 Get 1
In the next requirement, we need to use an external service, IOfferService, to determine eligibility for the "Buy 2 Get 1 Free" offer for certain items only. This will affect how the totals are calculated.
Step 1: Create the interface IOfferService
public interface IOfferService
{
bool IsEligibleForBuyTwoGetOne(string itemName);
}Step 2: Write the Failing Test Case
Write a test case to verify that the offer is correctly applied using the IOfferService. Note that a mocking framework should be used to mock the IOfferService behavior.
Test Case Setup:
Add a reference to a mocking library (like Moq) if not already added.
Modify the test constructor to now make use of new cart constructor which uses a service.
public class ShoppingCartTests
{
private readonly ShoppingCart _cart;
private readonly Mock<IOfferService> _mockOfferService;;
//xUnit creates a new instance of the test class for each test, so it is safe to share context!
public ShoppingCartTests()
{
_mockOfferService = new Mock<IOfferService>();
_cart = new ShoppingCart(_mockOfferService.Object);
}
//other code...
}Step 3: Write test case
Step 4: Modify the ShoppingCart (just to provision for enabling Injection of the service)
Guidance: Modify the
ShoppingCartclass to accept anIOfferServiceinstance via constructor injection. Initially, do not change any logic in the methods.Code:
Step 5: Run the Test (Confirm Failure)
Action: Run the test to confirm it fails, as the logic to use the
IOfferServiceis not implemented yet.
Step 6: Implement Logic to Pass the Test
Task: Implement the logic in the
ShoppingCartclass to use theIOfferServicefor determining offer eligibility.Guidance: Ensure that the
CalculateTotalCostmethod utilizes theIOfferServiceto apply discounts appropriately.
Step 7: Re-run the Test (Verify Success)
Action: Run the test again. The test should now pass, demonstrating that the shopping cart correctly interacts with the
IOfferService.
Last updated