0
public  class  QMT_ReviewSubmit {
public static QMT_Apex_Debug_Logs__c logger = new QMT_Apex_Debug_Logs__c(Apex_Class__c = 'QMT_ReviewSubmit', Type__c = 'UI');
public static String QMTThumbnail = System.Label.QMT_Thumbnail;
public static  String QMTcontentimage = System.Label.QMT_Content;
public static String QMTVideolink = System.Label.QMT_Video_link;
public static String editorProfile = System.Label.Commn_QMTEditor;
// Added by Shankar on Mar 06 2018 
public static QMT_Content__c QMTContent;

@AuraEnabled
public static Contact getCurrentUser(){
    user CurrentuserforSender = null;
    Contact USerAsContacts = null;
    try {
        CurrentuserforSender = [select Id, Username, Email, Name from User where Id = : UserInfo.getUserId()];
        USerAsContacts = [SELECT Id, Name, LastName, Email from Contact where Email  =: CurrentuserforSender.Email];
    } catch (QueryException ex) {
        insert new QMT_Apex_Debug_Logs__c(Apex_Class__c = 'QMT_ReviewSubmit', Type__c = 'UI',
                Message__c       = System.Label.QMT_Database_SOQL_Failure,
                Method__c        = 'getCurrentUser',
                Stack_Trace__c   = ex.getStackTraceString());
    }
    return USerAsContacts;
}

Test Class:

        @isTest
    public class QMT_ReviewSubmitTest {

        static  testMethod  void test1() {

            Profile p = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
            User u = new User(Alias = 'asdsad', Email = 'sasda@tasdtorg.com',
                              EmailEncodingKey = 'UTF-8', LastName = 'Testing', LanguageLocaleKey = 'en_US',
                              LocaleSidKey = 'en_US', ProfileId = p.Id,
                              TimeZoneSidKey = 'America/Los_Angeles', UserName = 'asd@das.com');
            insert u;
            Account a = new Account();
            a.name = 'test';
            insert a;

            Contact con = new Contact();
            con.LastName = 'test'; 
            con.AccountId = a.id;
            con.FirstName = 'test';
            con.Email = 'sasda@tasdtorg.com';
            con.QMT_PersonnelNbr__c = 2.0;
            insert con;

            QMT_Content__c c = new QMT_Content__c();
            c.name = 'test';
            c.QMT_Main_Body__c = 'test1tesdt2';
            c.Featured_Image_ID__c = 'test';
            c.QMT_Primary_Title__c = 'test';
            Recordtype RecordTypeIdcomm = [Select Id, Name From RecordType where Name = 'News / Alert' limit 1];
            c.RecordTypeId = RecordTypeIdcomm.id;
            QMT_Segment__c segment = new QMT_Segment__c();
            insert segment;
            c.SegmentId__c = segment.Id;
            insert c;

            QMT_Segment_Definition__c segmentDefinition = QMT_UnitTestData.createSegmentDefinition(segment.Id);
            insert segmentDefinition;
            system.assertEquals('sasda@tasdtorg.com', con.Email);

            List<String> allSelectedTopics = new List<String> {'test', 'test1'};
            QMT_CM_Topic_Master__c ci = new QMT_CM_Topic_Master__c();
            ci.TopicName__c = 'test';
            insert ci;

            QMT_CM_RestrictedAudience_Master__c ci2 = new QMT_CM_RestrictedAudience_Master__c();
            ci2.RAName__c = 'test';
            insert ci2;

            List<Folder> contentimagefolder   = [Select Id From Folder Where Name =: Label.QMT_Content];
            List<Folder> thumbnailimagefolder = [Select Id From Folder Where Name =: Label.QMT_Thumbnail];

            Document document = new Document();
            document.Body = Blob.valueOf('Some Text');
            document.ContentType = 'application/pdf';
            document.DeveloperName = 'QMT_ContentImage';
            document.IsPublic = true;
            document.Name = 'QMT content Image';
            if (contentimagefolder.size() > 0)
                document.FolderId = contentimagefolder[0].Id; //[select id from folder where name = 'QMT Content'].id;
            insert document;

            Document document1 = new Document();
            document1.Body = Blob.valueOf('Some Text');
            document1.ContentType = 'application/pdf';
            document1.DeveloperName = 'QMT_ThumbnailImage';
            document1.IsPublic = true;
            document1.Name = 'QMT Thumbnail Image';
            if (contentimagefolder.size() > 0)
                document1.FolderId = thumbnailimagefolder[0].id; //[select id from folder where name = 'QMT Content'].id;
            insert document1;

            QMT_Content_Topic_Jun__c CTopicJun = new QMT_Content_Topic_Jun__c(CM_Topic_Name__c = ci.Id, CommunicationContentName__c = c.Id);
            insert CTopicJun;
            // Recordtype RecordTypeIdcomm =[Select Id,Name From RecordType where Name='News / Alert' limit 1];

            String date1 = '2018-05-14T07:00:00.000Z'; 
            String date2 = 'May 14, 2018 7:00:00 AM';

            system.runAs(u) {
                  try{
                    Test.startTest();
                    QMT_ReviewSubmit QMT = new QMT_ReviewSubmit();
                    QMT_ReviewSubmit.getCurrentUser();
                     Test.stopTest();
               } catch (DmlException e) {
                }
            }
        }

Test class is passing but catch block is not covering? Can any one suggest me how to do that?

} catch (QueryException ex) {
        insert new QMT_Apex_Debug_Logs__c(Apex_Class__c = 'QMT_ReviewSubmit', Type__c = 'UI',
                Message__c       = System.Label.QMT_Database_SOQL_Failure,
                Method__c        = 'getCurrentUser',
                Stack_Trace__c   = ex.getStackTraceString());
    }
1

System.QueryException: List has no rows for assignment to SObject

This happens when the Object you are querrying does not meet criteria and returns 0 rows.

CurrentuserforSender = [select Id, Username, Email, Name from User where Id = : UserInfo.getUserId()];
USerAsContacts = [SELECT Id, Name, LastName, Email from Contact where Email  =: CurrentuserforSender.Email];

Thus one for the line from the above 2 should not return any rows for this exception to occur.

Lets consider line 1:

[select Id, Username, Email, Name from User where Id = : UserInfo.getUserId()];

This will always return row /records as there will always be a running user.

For the second line, a query on Contact. You need to write a test class which would make that querry fail. ie Contact's emailID and User's email id should not be same.(Or best no contact to be present)

 static  testMethod  void testCatchBlock() {
        boolean isExceptionCovered=false;
        Profile p = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
        User u = new User(Alias = 'asdsad', Email = 'sasda@tasdssstorg.com',
                          EmailEncodingKey = 'UTF-8', LastName = 'Testing', LanguageLocaleKey = 'en_US',
                          LocaleSidKey = 'en_US', ProfileId = p.Id,
                          TimeZoneSidKey = 'America/Los_Angeles', UserName = 'asd@das.com');
        insert u;
        try{
            System.runAs(u){
                 QMT_ReviewSubmit.getCurrentUser();

            }
        }catch(Exception e){
            System.assertEquals(e instanceOf QueryException)
        }
        System.assert(isExceptionCovered,'Opps exception was not covered')

 }
1

Looking at your code, it is quite simple to provoke the exception there, just create another Contact with the same email address in your test data, this will throw a query exception since you're casting the query to a single instance of contact (and not a list).

I would advise you to write two tests:

  • One for the passing context
  • Another for the not passing context

i.e. you can call them that way:

  • getCurrentUserPassTest
  • getCurrentUserFailTest

Your first test will pass with your current code, you just need to create another that replicates the first with a second Contact, and verify that the error is thrown/your log is inserted.

With that said, you should consider creating your common test data in a @TestSetup markup, then create test-specific data in each test.

1

The golden rule of unit testing is you only gain coverage for code that is executed as part of a unit test. The most important part of unit testing is to verify the behavior of your code using assertions.

To gain coverage for a catch block, you need to cause an appropriate exception to be thrown in the try block.

In this particular case, causing a System.QueryException is pretty easy, and Pranay's answer will do the trick. Sometimes, however, it's not so easy (how can you ensure that a System.DMLException would be thrown?).

One general approach that can be taken (to ensure that pretty much any exception can be thrown) is to use a static variable to control entry into a special if() block.

// This probably isn't great practice, but making the static var private
//   keeps other people/code from messing around with the value.
// The "@testVisible" annotation makes a variable (even a private one)
//   available to be read/written in a test.
@testVisible
private static Boolean induceException = false;

@AuraEnabled
public static Contact getCurrentUser(){
    user CurrentuserforSender = null;
    Contact USerAsContacts = null;
    try {
        // Since this is a static method, we can access static class variables
        // Since our variable is a boolean, there is no need to explicitly test 
        //   boolean == true.
        if(induceException){
            throw new System.QueryException('test exception');
        }

        CurrentuserforSender = [select Id, Username, Email, Name from User where Id = : UserInfo.getUserId()];
        USerAsContacts = [SELECT Id, Name, LastName, Email from Contact where Email  =: CurrentuserforSender.Email];
    } catch (QueryException ex) {
        insert new QMT_Apex_Debug_Logs__c(Apex_Class__c = 'QMT_ReviewSubmit', Type__c = 'UI',
                Message__c       = System.Label.QMT_Database_SOQL_Failure,
                Method__c        = 'getCurrentUser',
                Stack_Trace__c   = ex.getStackTraceString());
    }
    return USerAsContacts;
}

The test method for testing the catch block would be pretty simple

@isTest 
static void testCatchBlock(){
    QMT_ReviewSubmit testInstance = new QMT_ReviewSubmit();

    QMT_ReviewSubmit.induceException = true;

    Contact result;
    test.startTest();
    result = testInstance.getCurrentUser();
    test.stopTest();

    // Don't forget to make assertions!
    // Good assertions to make would be checking that the return value
    //   is what you expect it to be, and that you did successfully create
    //   a QMT_Apex_Debug_Logs__c record
}

One thing to keep in mind is that you can have more than one test method in a test class. In fact, I'd argue that you should have more than one test method. By breaking your test scenarios apart, so that each test method covers a single scenario, you'll probably find that the individual test methods are easier to write. Also, if one of your test methods fails, you'll have a much better idea of precisely what needs to be fixed (compared to mashing everything into a single test method).

  • +1 for using more test methods than one big one. – Folkert May 16 '18 at 14:18

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.