Trapdoor In The Sun

Alan Shanahan, Technician & Consultant

1 Comment Apex Test Assertions: It Must Be a Real Test

In the course of building automated tests, it’s always good practice to pepper your test code with Assert statements to ensure your code is functioning as you would expect throughout. But, as I’ve seen more than one example of the specific behaviour in the first code section below, I think it’s something I should point out.

On first glance, it looks like the assertion is doing the right thing. But if you think about it, it’s not a real test. It only tests that the in-memory variable testAcc.Name has the value originally assigned to it a couple of lines back.

// Example 1. An in-memory-based test
Account testAcc = new Account();
testAcc.Name = 'Testing 123';
insert testAcc;


What it really needs to do, so that it becomes a “real” test is for the test method to query the database record just inserted and to retrieve the Name value from the record, then check it against the expected value, as shown below.

// Example 2. A database-based test
Account testAcc = new Account();
testAcc.Name = 'Testing 123';
insert testAcc;

Account checkAcc = [SELECT Name FROM Account WHERE Id = :testAcc.Id];

This example is, perhaps, not a great real-world scenario but I feel it illustrates the problem well.

Happy coding, if it’s your thing.