+ Start a Discussion
Melanie VOYMANTMelanie VOYMANT 

apex class test need help

Hi there, 

I did a test class for my controller but I can't find my error, could you please help me? I'll give you an example of my controller and my test class.

Controller : 

public with sharing class AdvancedAnalyseController {
    @AuraEnabled
    public static void cloneThisAnalyse(Id analyseId, Integer nombreA) {
        String queryAnalyse = 'SELECT Id, ';
        queryAnalyse += buildCustomFieldsQuery(Analyse__c.getSObjectType());
        queryAnalyse = queryAnalyse.removeEnd(', ') + ' FROM Analyse__c WHERE Id = \'' + analyseId + '\'';
        mDebugUntruncated(queryAnalyse);
        List<Analyse__c> aList = Database.query(queryAnalyse);
        if (aList.isEmpty()) {
            AuraHandledException ex = new AuraHandledException('NO_ANALYSE');
            ex.setMessage('NO_ANALYSE');
            throw ex;
        }
        List<Analyse__c> analyseClone = new List<Analyse__c>();
         for (Integer i=0; i<nombreA; i++) {
            Analyse__c newAnalyse = aList.get(0).clone();
            newAnalyse.Clone__c = true;
            analyseClone.add(newAnalyse);
         }
        insert analyseClone;
        
    }
    @TestVisible
    private static String buildAllFieldsQuery(Schema.SObjectType targetSObjectType) {
        Map<String, Schema.SObjectField> fieldMap = targetSObjectType.getDescribe().fields.getMap();
        String query = '';
        for (String key : fieldMap.keySet()) {
            Schema.SObjectField field = fieldMap.get(key);
            Schema.DescribeFieldResult result = field.getDescribe();
            query += result.getName() + ', ';
        }
        return query.removeEnd(', ');
    }
    @TestVisible
    private static String buildCustomFieldsQuery(Schema.SObjectType targetSObjectType) {
        Map<String, Schema.SObjectField> fieldMap = targetSObjectType.getDescribe().fields.getMap();
        String query = '';
        for (String key : fieldMap.keySet()) {
            Schema.SObjectField field = fieldMap.get(key);
            Schema.DescribeFieldResult result = field.getDescribe();
            if (result.isCustom()) {
                query += result.getName() + ', ';
            }
        }
        return query.removeEnd(', ');
    }
    public static void mDebugUntruncated(String sMsg) {
        for (Integer i = 0; i < sMsg.length(); i=i+300) {
            Integer iEffectiveEnd = (i+300 > (sMsg.length()-1) ? sMsg.length()-1 : i+300);
            System.debug(sMsg.substring(i,iEffectiveEnd));
        }
    }
}

Test class : 

@isTest
private class AdvancedAnalyseControllerTest {
    @TestSetup
    static void makeData() {
        Account acc = new Account (Name='Test_Account', Phone='0123456789');
        insert acc;
        PAD.ApexForcedBypass.remove('AP001');
        Agence__c ag = new Agence__c(Code_agence__c = 'IDF',Code_agence_telephone__c = '98254');
        insert ag;
        Bulle__c bulle = new Bulle__c();
        bulle.Name = 'Bulle de test';
        bulle.Date_cr_ation__c = Date.today();
        insert bulle;
        opportunity opp = new Opportunity(Name='Test_Opp', Code_agence__c='IDF', StageName='Prospection', accountid=acc.Id,
                                            CloseDate=Date.today() , Site_Ville__c='Paris');
        opp.Bulle__c = bulle.Id;
        opp.Agence_code__c = ag.Id;
        insert opp;
        Affaire__c affaire1 = new Affaire__c();
        affaire1.Name = 'Affaire test 1';
        affaire1.Bulle__c = bulle.Id;
        affaire1.Agence__c = ag.Id;
        affaire1.Opportunit__c = opp.Id;
        insert affaire1;
        Chantier__c chantier = new Chantier__c();
        chantier.Name = 'Chantier Test';
        chantier.Compte__c = acc.Id;
        chantier.Opportunite__c = opp.Id;
        chantier.Code_agence__c = ag.Id;
        chantier.Bulle_del__c = bulle.Id;
        chantier.Affaire__c = affaire1.Id;
        insert chantier;
        Analyse__c analyse = new Analyse__c();
        analyse.Etat__c = 'Création = bon de commande';
        analyse.Nature__c = 'Mesure environnementale';
        analyse.Chantier__c = chantier.Id;
        insert analyse;
    }
    @isTest
    static void testmDebugisOK() {
        AdvancedAnalyseController.mDebugUntruncated('test');
    }
    @isTest
    static void testbuildFullListisOk() {
        String fieldList = AdvancedAnalyseController.buildAllFieldsQuery(Analyse__c.getSObjectType());
        System.assertNotEquals(null, fieldList);
    }
    @isTest
    static void testbuildCustomListisOk() {
        String fieldList = AdvancedAnalyseController.buildCustomFieldsQuery(Analyse__c.getSObjectType());
        System.assertNotEquals(null, fieldList);
    }
    @isTest
    static void testCloneAnalyseisOk() {
        PAD.ApexForcedBypass.remove('AP001');
        Analyse__c analyse = [SELECT Id, Chantier__c FROM Analyse__c];
        Test.startTest();
        List<Analyse__c> analyseClone = AdvancedAnalyseController.cloneThisAnalyse();
        for (Integer i=0; i<10; i++) {
            Analyse__c newAnalyse = analyse.clone();
            newAnalyse.Clone__c = true;
            analyseClone.add(newAnalyse);
         }
        Test.stopTest();
        List<Analyse__c> analyses = [SELECT Id FROM Analyse__c];
        System.assertEquals(1, analyses.size());
    }
    @isTest
    static void testCloneAnalyseisNOK() {
        PAD.ApexForcedBypass.remove('AP001');
        Analyse__c analyse = [SELECT Id FROM Analyse__c];
        delete analyse;
        Test.startTest();
        try {
        List<Analyse__c> analyseClone = AdvancedAnalyseController.cloneThisAnalyse();
            for (Integer i=0; i>10; i++) {
            Analyse__c newAnalyse = analyse.clone();
            newAnalyse.Clone__c = true;
            analyseClone.add(newAnalyse);
         }
        } catch (AuraHandledException ex) {
            System.assertEquals('NO_ANALYSE', ex.getMessage());
            return;
        }
        Test.stopTest();
        System.assert(false);
    }
}
pconpcon
I'll start by saing that your tests don't really do much and aren't tests that I would like to see in my org.  Each test should include assert methods that actually test that you're methods are doing what they expect and just checking that a list isn't null is not a good test.  Additionally, you never said how your tests are erroring, just that they are.  I'd start by reworking your tests so that they actually have the expected data being asserted.  I've taken the liberty of refactoring / reformatting your main code to help with this discussion.
 
public with sharing class AdvancedAnalyseController {
    public static String NO_ANALYSE = 'NO_ANALYSE'
    @AuraEnabled
    public static void cloneThisAnalyse(Id analyseId, Integer nombreA) {
        List<String> query = new List<String> {
            'select ' + buildCustomFieldsQuery(Analyse__c.getSobjectType()),
            'from ' + Schema.sObjectType.Analyse__c.getName(),
            'where Id = \'' + analyseId + '\''
        }
        
        List<Analyse__c> aList = Database.query(String.join(query, ' '));
        
        if (aList.isEmpty()) {
            throw new AuraHandledException(NO_ANALYSE);
        }
        
        List<Analyse__c> clones = new List<Analyse__c>();
        
        for (Analyse__c analyse : aList) {
            Analyse__c newAnalyse = analyse.clone();
            newAnalyse.Clone__c = true;
            clones.add(newAnalyse);
        }
        
        insert clones;
    }
    
    @TestVisible
    private static String buildAllFieldsQuery(Schema.SObjectType targetSObjectType) {
        Map<String, Schema.SObjectField> fieldMap = targetSObjectType.getDescribe().fields.getMap();
        List<String> fields = new List<String>();
        fields.addAll(fieldMap.keySet());
        
        return String.join(fields, ',');
    }
    
    @TestVisible
    private static String buildCustomFieldsQuery(Schema.SObjectType targetSObjectType) {
        Map<String, Schema.SObjectField> fieldMap = targetSObjectType.getDescribe().fields.getMap();
        List<String> fields = '';
        
        for (String key : fieldMap.keySet()) {
            Schema.DescribeFieldResult result = fieldMap.get(key).getDescribe();
            
            if (result.isCustom()) {
                fields.add(result.getName());
            }
        }
        return String.join(fields, ',');
    }   
}

Then you can write your tests as follows.  You'll want to add tests that cover all the facets and all the conditional logic you have in place.  You'll also want to write explict tests covering the other methods.  I remove the debug one since it shouldn't go to production and is not something you can validly test.
@isTest
private class AdvancedAnalyseControllerTest {
    @TestSetup
    static void makeData() {
        Account acc = new Account (
            Name = 'Test_Account',
            Phone = '0123456789'
        );
        insert acc;

        PAD.ApexForcedBypass.remove('AP001');

        Agence__c ag = new Agence__c(
            Code_agence__c = 'IDF',
            Code_agence_telephone__c = '98254'
        );
        insert ag;

        Bulle__c bulle = new Bulle__c(
            Name = 'Bulle de test',
            Date_cr_ation__c = Date.today()
        );
        insert bulle;

        opportunity opp = new Opportunity(
            Name = 'Test_Opp',
            Code_agence__c = 'IDF',
            StageName = 'Prospection',
            AccountId = acc.Id,
            CloseDate = Date.today(),
            Site_Ville__c='Paris',
            Bulle__c = bulle.Id,
            Agence_code__c = ag.Id
        );
        insert opp;

        Affaire__c affaire1 = new Affaire__c(
            Name = 'Affaire test 1',
            Bulle__c = bulle.Id,
            Agence__c = ag.Id,
            Opportunit__c = opp.Id
        };
        insert affaire1;

        Chantier__c chantier = new Chantier__c(
            Name = 'Chantier Test',
            Compte__c = acc.Id,
            Opportunite__c = opp.Id,
            Code_agence__c = ag.Id,
            Bulle_del__c = bulle.Id,
            Affaire__c = affaire1.Id
        );
        insert chantier;

        Analyse__c analyse = new Analyse__c(
            Etat__c = 'Création = bon de commande',
            Nature__c = 'Mesure environnementale',
            Chantier__c = chantier.Id
        );
        insert analyse;
    }

    static void testMethod cloneTest() {
        Analyse__c analyse = [
            select Id,
                Etat__c,
                Nature__c,
                Chantier__c
            from Analyse__c
        ];

        Test.startTest();

        AdvancedAnalyseController.cloneThisAnalyse(analyse, 2);

        Test.stopTest();

        List<Analyse__c> results = [
            select Id,
                Etat__c,
                Nature__c,
                Chantier__c,
                Clone__c
            from Analyse__c
            where Id != :analyse.Id
        ];

        System.assertEquals(2, results.size(), 'Did not get the expected number of results');
        for (Analyse__c result : results) {
            System.assert(result.Clone__c, 'Should be a clone');
            System.assertEquals(analyse.Etat__c, result.Etat__c, 'Did not get the expected value');
            System.assertEquals(analyse.Nature__c, result.Nature__c, 'Did not get the expected value');
            System.assertEquals(analyse.Chantier__c, result.Chantier__c, 'Did not get the expected value');
        }
    }
}
NOTE: The code above has not been tested and may contain typographical and / or logical errors.
NOTE: Please use the "Add a Code Sample" button (icon <>) when adding code to make it easier to read and reference.