2

enter image description here

Hi All,

Can anyone help me how to write unit test for apex exception? I assume red lines are not into code coverage. Let me correct if i am wrong

4
  • 1
    it would be great if you can update your question with your whole code. in first sight I can see that if you will make userid length less than 1 it will cover that line. – Himanshu Oct 30 '15 at 13:59
  • Ok, this is same where i couldnt cover. public getUserInfo() { user = [SELECT id, email, username, usertype, communitynickname, timezonesidkey, languagelocalekey, firstname, lastname, phone, title, street, city, country, postalcode, state, localesidkey, mobilephone, extension, fax, contact.email FROM User WHERE id = :UserInfo.getUserId()]; // guest users should never be able to access this page if (user.usertype == 'GUEST') { throw new NoAccessException(); } – user2721787 Oct 30 '15 at 14:33
  • create a new test user inside your code and set user.usertype="Guest" while creating that user. – Himanshu Oct 30 '15 at 23:42
  • In this case i can not write usertype. But i re write the code to check for profile and user licence instead od usertype. So i created test user in a way to fall into this exception. Thanks to Kevin P. I had to create a correct test data. – user2721787 Nov 2 '15 at 7:56
6

Morning.

The general pattern for testing exceptions is this:

  1. Create your data.
  2. Start the Test.
  3. Create a boolean variable, DidThrowException = false.
  4. Run your code inside a Try/Catch block.
  5. Catch only the type of exception that your code throws. In this case, NoAccessException.
  6. If the Catch block is run, set your boolean variable to True.
  7. Stop your Test.
  8. Assert that the boolean is true.
  9. ... $$$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.