You need to sign in to do that
Don't have an account?
BrianWK
Best practices - best way to use System.debug and system.assert
Hey everyone,
I've been dabbling in apex code for a while. I've always used system.assert to check my code and view the apex error in my triggers. Once I confirmed I've gotten the right output/input I comment out the system.assert.
I've been seeing a lot of board messages suggesting using system.debug. I've looked at the dev. manual and I'm a bit confused. How and when do I use system.debug? Why use system.debug over system.assert?
Any real life examples including the system.debug and the output of system.debug would be appreciated as well.
Thanks!
System.debug
Is a way how you can output data. You can see the output statement in the debug log. you can use this in every apex method or trigger
System.assert
Is a unit testing statement. You can check wheather the output your code is as expected.This statement is used in testmethod, if the assertion failes your whole testmethod fails and you can't depoly your code.
Example
Account a = new Account(Name = 'Test AG'); try{ insert a; }catch(System.Exception e){ System.debug('Exception occured: ' + e); System.assert(false); }
System.debug('This is the id from the created account: '+ a.Id);
System.assertEquals([Select a.Name from Accuont a where a.Id = :a.Id limit 1].Name ,'Test AG');
All Answers
System.debug
Is a way how you can output data. You can see the output statement in the debug log. you can use this in every apex method or trigger
System.assert
Is a unit testing statement. You can check wheather the output your code is as expected.This statement is used in testmethod, if the assertion failes your whole testmethod fails and you can't depoly your code.
Example
Account a = new Account(Name = 'Test AG'); try{ insert a; }catch(System.Exception e){ System.debug('Exception occured: ' + e); System.assert(false); }
System.debug('This is the id from the created account: '+ a.Id);
System.assertEquals([Select a.Name from Accuont a where a.Id = :a.Id limit 1].Name ,'Test AG');
Using both together can be helpful in the testing process and system.debug is also helpful when troubleshooting once in production.
As you have found, assert and assertEquals allows you to test an expected condition within your test methods for establishing correct behavior in your code.
System.debug allows you to write information in string format to the debug log. This can be simple text such as "...calling xyz function..." or writing actual variable values to the log. This allows you to see not only what is happening while you are testing (along with the assert functions), but your debug statements can reside outside your test methods giving you the ability to write to the debug log when in production. This way if something goes wrong in production you can look at the detail captured in the debug log and any additional information you may be writing to the debug log via the System.debug method.