Trapdoor In The Sun

Alan Shanahan, Technician & Consultant

Force.com Apex Test Assertions: It Must Be a Real Test

1 Comment

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;

System.assertEquals('Testing123',testAcc.Name);

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];
System.assertEquals(checkAcc.Name,testAcc.Name);

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.

Author: Alan Shanahan

Cloud computing professional, amateur drummer and other things. Doesn't take himself too seriously. He's got a fever ... and the only prescription is more cowbell.

One thought on “Force.com Apex Test Assertions: It Must Be a Real Test

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s