Writing Behaviour Verification Unit Tests

Last time we saw how to add a mock implementation of our component to our unit test class using the apex-mocks-generator tool.

Now we have everything in place to verify the behaviour of our components in our unit test.

So to take an example, say we want to verify that a BillingService component interacts correctly with a CreditCardProcessor component. To do this we can write a behaviour verification unit test like this:

@isTest
private class BillingServiceUnitTest
{
    @isTest
    static void chargingCustomerShouldProcessCreditCardPayment()
    {
        // Given
        ApexMocks mocks = new ApexMocks();
        CreditCardProcessor.ICreditCardProcessor mockCreditCardProcessor = new MockCreditCardProcessor(mocks);

        Order order = new Order();
        // fill in order details
        order.Id = IDGenerator.generate(Order.SObjectType);

        // When
        BillingService billingService = new BillingService(mockCreditCardProcessor);
        billingService.chargeCustomer(order);

        // Then
        ((CreditCardProcessor.ICreditCardProcessor) mocks.verify(mockCreditCardProcessor)).processPayment(order);
    }
}

Anyone familiar with mockito syntax should recognise the verify() immediately, apart from the cast. Apex has its limits!

The important thing here is the the ApexMocks framework is going to ensure that the correct method on the CreditCardProcessor was called with the correct arguments, when the BillingService charges a customer.

Notice that we didn’t need to insert the Order object into the database, so this test runs very quickly. We also used the ApexMocks IDGenerator to generate a fake Id for the Order object.

2 thoughts on “Writing Behaviour Verification Unit Tests

  1. Pingback: Verify call’s order in Apex unit tests – XoNoX Force

  2. Pingback: Answering with Apex Mocks – XoNoX Force

Leave a comment