• AmberTaylor
  • NEWBIE
  • 30 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 4
    Replies
Hello, 

I have tried to generate a random number that changes any time my function is called using Math.Random. but it appears that the number is still the same in the context, and never change : 
here is what i've done. 

The function : 
public static Integer getRandomNumber(Integer listSize){
        Integer randomNumber = Integer.valueof(Math.random() * listSize);
        System.debug('randomNumber' + randomNumber);
        return randomNumber;
    }

When i call the previous function :
List<trailheadapp__User_Badge__c> recordsToInsert = new List<trailheadapp__User_Badge__c>();
        for(Integer i=0; i<300; i++) {
            String randomString = badgeStatus[getRandomNumber(listSize)];
            String randomBadge = badgeList[getRandomNumberForBadge(listBadgeSize)];
            String randomUserID = idList[getRandomId(listIdSize)];
            System.debug('RANDOM USER ID = '+randomUserID);
            trailheadapp__User_Badge__c newJunctionRecord = new trailheadapp__User_Badge__c (trailheadapp__External_ID__c = '0050E00000823JEQAY-a093X00001SmGRWQA'+i,trailheadapp__Status__c = randomString, trailheadapp__Badge__c = randomBadge, trailheadapp__User__c = randomUserID);
            recordsToInsert.add(newJunctionRecord);
        }
        insert recordsToInsert;
The random number remains the sames for all records inserted, what i want is that number changes for every record. 

Does someone see something wrong ?

Ty in advance for help
Amber
Hello, 

Is someone available to help me with a test class ?

here is my code :
public class TokenGenerator_CTL {
    private static final String CNONCE = String.valueOf(Crypto.getRandomLong()); 

    //random number ;
    public String finalUrl { get; set; }

    public TokenGenerator_CTL() {
       
       
       //retrieve custom settings TokenSettings__c that contains credentials to access insideBoard Widget
       InsideboardSettings__c oIBSettings = [ SELECT PRIVATE_KEY__c, PUBLIC_KEY__c, SUBDOMAIN__c, WIDGET_PATH__c FROM TokenSettings__c LIMIT 1 ];
       System.debug('oIBSettings Value = ' + oIBSettings);
       // Get current user ID
       String userId = UserInfo.getUserId();

       // path to access the Widget and custom settings fields to retrieve keys
       String Widget_Path = '/query-auth-access/project/__/user/UID/one/time/only/to/widget/show';
       String WP = oIBSettings.WIDGET_PATH__c;
       if (!string.isBlank(WP)){ 
           Widget_Path = '/query-auth-access/project/__/user/UID/one/time/only/redirect/project/' +  WP + '/to/widget/show' ;
        }
        System.debug('WidgetPATH Value = ' + Widget_Path);

       String Client_Private = oIBSettings.PRIVATE_KEY__c; 
       String Client_Public  = oIBSettings.PUBLIC_KEY__c; 
       String Base_URL = 'https://' + oIBSettings.SUBDOMAIN__c + '.thisSite.com';
       //this allows to change UID string with retrieved userId variable value
       String path = Widget_Path.replace('UID', getUserFederationId (userId));
       // complete url
       String url = Base_URL + path;
       String strippedURL = Base_URL.removeStart('https://');
       long timestamp = Datetime.now().getTime(); String cnonce = CNONCE + timestamp;
       String tmpParamString = 'cnonce=' + EncodingUtil.urlEncode (cnonce, 'UTF-8') + '&key=' + EncodingUtil.urlEncode(Client_Public, 'UTF-8') + '&timestamp=' + timestamp/1000 ;
       String sign1 = 'GET\nhttps\n' + strippedURL + '\n'+ path.toLowerCase() + '\n' + tmpParamString;
       String paramString = tmpParamString + '&signature=' + EncodingUtil.urlEncode(getSignature(sign1, Client_Private), 'UTF-8');
       finalUrl = url + '?' + paramString;
       System.debug('<======== Final URL Value = ' + finalURL + ' ========>');
    }
    
    // function that returns signature, that will be use to get final URL 
    private static String getSignature (String toSign, String privateKey) {
     Blob signatureBlob = Crypto.generateMac('HmacSHA256', Blob.valueOf(toSign) , Blob.valueOf(privateKey));
     String signature = EncodingUtil.base64Encode(signatureBlob); 
     System.debug('Signature value = ' + signature + ' ========>');
     return signature;
    }

    // function that returns current user Federation Id
    private String getUserFederationId(String userId) {
     String federationId = [SELECT FederationIdentifier FROM User WHERE Id = :userId].FederationIdentifier;
     System.debug('<======== FederationId value = ' + federationId + ' ========>') ;
     return (federationId == null) ? '' : federationId;
    }
}

Here My starting TestClass : 
public with sharing class TokenGenerator_CTL_TST {
    @isTest public static void TestTokenGenerator() {
        Profile profileId = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];

        User usr = new User(LastName = 'Test',
            FirstName='EML',
            Alias = 'EmlT',
            Email = 'eml.test@gmail.com',
            Username = 'eml.test@gmail.com',
            ProfileId = profileId.id,
            TimeZoneSidKey = 'GMT',
            LanguageLocaleKey = 'en_US',
            EmailEncodingKey = 'UTF-8',
            LocaleSidKey = 'en_US',
            FederationIdentifier = 'IJK435'
            );
        insert usr;

        TokenGenerator_CTL testTry = new TokenGenerator_CTL();
        
        System.runAs(usr) {
            Test.startTest();
            RestRequest req = new RestRequest(); 
            RestResponse res = new RestResponse();
            req.requestURI = testTry.finalURL; 
            req.httpMethod = 'GET';
            req.addHeader('Content-Type', 'application/json'); 
            RestContext.request = req;
            RestContext.response = res;
            Test.stopTest();   
        }
    }
}

Any help on this topic would be appreciated ! TY in advance
Amber
Hello there,

I have an issue with my trigger, here is the error message that i get :  : System.DmlException: Update failed. First exception on row 0 with id a1G0E000001T6wgUAC; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = a1G0E000001T6wg) is currently in trigger OC_EquipementUpdateWithReferentiel, therefore it cannot recursively update itself: [] Class.OC_EquipementTRIGGER.updateParent: line 181, column 1 Trigger.OC_EquipementUpdateWithReferentiel: line 23, column 1: []: Class.OC_EquipementTRIGGER.UpdateEquipWithReferentiel: line 73, column 1

Here is my trigger Class :
public class OC_EquipementTRIGGER {
    public static Boolean runTrigger = true;
    Public static Boolean firstcall=true;
    
    // Trigger 1 active when record type = 'Equipement referentiel'
    public static void UpdateEquipWithReferentiel(List<OC_Equipement__c> equipRefCreated) {
        list<OC_Equipement__c> updateParent = new list<OC_Equipement__c>();
        
        List<String> IMEICodeRef = new List<String>();
        List<String> SILCodeRef = new List<String>();
        List<String> serialNumberRef = new List<String>();
        
        String equipCollab='0120E000001bH9x';
        String equipReferentiel ='0120E000001bHA2';
        
        List <OC_Equipement__c> updateChildren= new List<OC_Equipement__c>();   
        
        Map<String, String> equipRefSIL = new Map<String, String>();
        Map<String, String> equipRefIMEI = new Map<String, String>();
        Map<String, String> equipRefSerial = new Map<String, String>();
        
        //Store all identifiers for newly created / updated records type référentiel in variables
        for (OC_Equipement__c e : equipRefCreated) {
            if (e.RecordTypeId == equipReferentiel) {
                if(e.NumeroIMEIiPhone__c != null) {
                    IMEICodeRef.add(e.NumeroIMEIiPhone__c);
                } else if(e.NumeroSIL__c != null) {
                    SILCodeRef.add(e.NumeroSIL__c);
                } else if(e.NumeroSerie__c != null) {
                    serialNumberRef.add(e.NumeroSerie__c);
                } 
            }
        }
        
        //  List of equipements collaborateur corresponding to newly created referentiel equipements
        List <OC_Equipement__c> equipList = [Select ID,Name, NumeroTelephone__c, NumeroSIL__c, EquipementReferentiel__c, TypeEquipement__c,  NumeroSerie__c, NumeroIMEIiPhone__c, DateCreation__c,DeclarationEquipement__r.Nom__c , Statut__c 
                                             FROM OC_Equipement__c
                                             where ((NumeroSIL__c in :SILCodeRef) OR (NumeroSerie__c in :serialNumberRef) OR (NumeroIMEIiPhone__c in :IMEICodeRef)) AND RecordTypeId =:equipCollab];
        
        for (OC_Equipement__c eq:equipRefCreated){
            if (equipList.size() > 0 ){
                if(eq.NumeroIMEIiPhone__c != null) {
                    equipRefIMEI.put(eq.NumeroIMEIiPhone__c, eq.ID);
                } else if(eq.NumeroSIL__c != null ) {
                    equipRefSIL.put(eq.NumeroSIL__c, eq.ID);
                } else if(eq.NumeroSerie__c != null) {
                    equipRefSerial.put(eq.NumeroSerie__c, eq.ID);
                } 
            }
        } 
        
        System.debug('==equipRefSIL==' + equipRefSIL);
        System.debug('==equipRefIMEI==' + equipRefIMEI);
        System.debug('==equipRefSerial==' + equipRefSerial);
        
        for(OC_Equipement__c equip: equipList) {
            if(equipRefIMEI.containsKey(equip.NumeroIMEIiPhone__c)) {
                equip.EquipementReferentiel__c = equipRefIMEI.get(equip.NumeroIMEIiPhone__c);
                equip.statut__c = 'Présent et Utilisé';
                updateChildren.add(equip);
            } else if(equipRefSIL.containsKey(equip.NumeroSIL__c)) {
                equip.EquipementReferentiel__c = equipRefSIL.get(equip.NumeroSIL__c);
                equip.statut__c = 'Présent et Utilisé';
                updateChildren.add(equip);
            } else if(equipRefSerial.containsKey(equip.NumeroSerie__c)) {
                equip.EquipementReferentiel__c = equipRefSerial.get(equip.NumeroSerie__c);
                equip.statut__c = 'Présent et Utilisé';
                updateChildren.add(equip);
            }
            
            System.debug(equip.EquipementReferentiel__c + ' = equip.EquipementReferentiel__c value');
        }
        update updateChildren;
        System.debug(updateChildren + ' = updateChildren list value');
        
    }
    
    
    //trigger2  active when record type = 'Equipement Collaborateur'
    public static void UpdateEquip(List<OC_Equipement__c> equipCollabCreated) {
        List<String> IMEICode = new List<String>();
        List<String> SILCode = new List<String>();
        List<String> serialNumber = new List<String>();
        
        String equipCollab='0120E000001bH9x';
        String equipReferentiel ='0120E000001bHA2';
        
        List <OC_Equipement__c> equipToUpdate = new List<OC_Equipement__c>();  
        
        Map<String, String> equipCollabSIL = new Map<String, String>();
        Map<String, String> equipCollabIMEI = new Map<String, String>();
        Map<String, String> equipCollabSerial = new Map<String, String>();
        
        
        //Store all identifiers for newly created / updated records type equip collaborateur in variables
        for (OC_Equipement__c eq : equipCollabCreated) {
            if (eq.RecordTypeId == equipCollab) {
                if(eq.NumeroIMEIiPhone__c != null) {
                    IMEICode.add(eq.NumeroIMEIiPhone__c);
                } else if(eq.NumeroSIL__c != null ) {
                    SILCode.add(eq.NumeroSIL__c);
                } else if(eq.NumeroSerie__c != null) {
                    serialNumber.add(eq.NumeroSerie__c);
                } 
            }
        }
        
        //  List of equipements référentiel corresponding to newly created team equipements
        List <OC_Equipement__c> equipRefList = [Select ID,Name, NumeroTelephone__c, NumeroSIL__c, EquipementReferentiel__c, TypeEquipement__c,  NumeroSerie__c, NumeroIMEIiPhone__c, DateCreation__c,DeclarationEquipement__r.Nom__c , Statut__c 
                                                FROM OC_Equipement__c
                                                where ((NumeroSIL__c in :SILCode) OR (NumeroSerie__c in :serialNumber) OR (NumeroIMEIiPhone__c in :IMEICode)) AND RecordTypeId =:equipReferentiel];
        
        
        for (OC_Equipement__c eqList:equipRefList){
            if (equipRefList.size() > 0 ){
                if(eqList.NumeroIMEIiPhone__c != null) {
                    equipCollabIMEI.put(eqList.NumeroIMEIiPhone__c, eqList.ID);
                } else if(eqList.NumeroSIL__c != null ) {
                    equipCollabSIL.put(eqList.NumeroSIL__c, eqList.ID);
                } else if(eqList.NumeroSerie__c != null) {
                    equipCollabSerial.put(eqList.NumeroSerie__c, eqList.ID);
                } 
            }
        }
        
        System.debug('==equipCollabSIL==' + equipCollabSIL);
        System.debug('==equipCollabIMEI==' + equipCollabIMEI);
        System.debug('==equipCollabSerial==' + equipCollabSerial);
        
        for(OC_Equipement__c e: equipCollabCreated) {
            if(e.RecordTypeId == equipCollab)  {
                if(equipCollabIMEI.containsKey(e.NumeroIMEIiPhone__c)) {
                    e.EquipementReferentiel__c = equipCollabIMEI.get(e.NumeroIMEIiPhone__c);
                    e.Key__c = e.NumeroIMEIiPhone__c;
                } else if(equipCollabSIL.containsKey(e.NumeroSIL__c)) {
                    e.EquipementReferentiel__c = equipCollabSIL.get(e.NumeroSIL__c);
                    e.Key__c = e.NumeroSIL__c;
                } else if(equipCollabSerial.containsKey(e.NumeroSerie__c)) {
                    e.EquipementReferentiel__c = equipCollabSerial.get(e.NumeroSerie__c);
                    e.Key__c = e.NumeroSerie__c;
                    
                }
                OC_Equipement__c newEq = new OC_Equipement__c(id =e.id );
                equipToUpdate.add(newEq);
                equipToUpdate.add(e);
                // System.debug(e.EquipementReferentiel__c + ' = e.EquipementReferentiel__c value');
            }
        }  
        System.debug('*************'+equipToUpdate + ' = equipToUpdatevalue ******');
        //create a map that will hold the values of the equipToUpdate list 
        map<id,OC_Equipement__c> accmap = new map<id,OC_Equipement__c>();
        
        //put all the values from the list to map. 
        accmap.putall(equipToUpdate);
    }

    public static void updateParent(List<OC_Equipement__c> equipCreated) {
        List<id> listIdsCreatedEquip = new List<id>();
        for (OC_Equipement__c c : equipCreated) {
            system.debug('<========= '+c.EquipementReferentiel__c + ' c.EquipementReferentiel__c  value =========>');
            if(c.EquipementReferentiel__c != null) {
                listIdsCreatedEquip.add(c.EquipementReferentiel__c);   
            }
        }
        
        if(listIdsCreatedEquip.size()> 0) {
            System.debug('<================= listIdsCreatedEquip list value on SAVE() = ' + listIdsCreatedEquip + '=======>');
            Map<ID, OC_Equipement__c> parentEquip = new Map<ID, OC_Equipement__c>( [ SELECT ID, Statut__c from OC_Equipement__c where ID in :listIdsCreatedEquip ]);
            System.debug('<================= parentEquip MAP list value on SAVE() = ' + parentEquip + '=======>');
            OC_Equipement__c myParentEquip = new OC_Equipement__c();
            List<OC_Equipement__c> updateParents = new List<OC_Equipement__c>();
            
            if(parentEquip.size() > 0) {
                for(OC_Equipement__c childEquip : equipCreated) {
                    myParentEquip = parentEquip.get(childEquip.EquipementReferentiel__c);
                    myParentEquip.Statut__c = 'Présent et Utilisé';
                    System.debug('<================= myParentEquip list value on SAVE() = ' + myParentEquip + '=======>');
                    updateParents.add(myParentEquip);
                }
                runTrigger = false;
                update updateParents;
                System.debug('<================= updateParents list value on SAVE() = ' + updateParents + '=======>');
            } 
        }
    }
}

Here is the trigger itself : 
 
trigger OC_EquipementUpdateWithReferentiel on OC_Equipement__c (before insert, before update,after insert, after update) {
     String equipCollab='0120E000001bH9x';
     String equipReferentiel ='0120E000001bHA2';
    
     if (trigger.isBefore) {
        if(trigger.isInsert || trigger.isUpdate) {
           for(OC_Equipement__c e:trigger.new) {
                 if(e.RecordTypeId == equipReferentiel) {
                     OC_EquipementTRIGGER.UpdateEquipWithReferentiel(trigger.new);
                 } else if (e.RecordTypeId == equipCollab ) {
                     OC_EquipementTRIGGER.UpdateEquip(trigger.new);
                 }
           }
        } 
     } else {
         if(trigger.isAfter && (trigger.isInsert || trigger.isUpdate)) {
             for(OC_Equipement__c e:trigger.new) {
                 if(e.RecordTypeId == equipReferentiel) {
                     OC_EquipementTRIGGER.UpdateEquipWithReferentiel(trigger.new);
                 } else if (e.RecordTypeId == equipCollab){
                     if(OC_EquipementTRIGGER.firstcall == true) {
                          OC_EquipementTRIGGER.firstcall = false;
                            OC_EquipementTRIGGER.updateParent(trigger.new);
                     } 
                 }
             }
         }
     }
}
There is a particularity in here : parent and child are on same object, but with different record type. 
When i create a child record and a parent is find, i need to update parent status to say it is used by someone. (in method update parent) that create this meessage error when i try to update a parent equipment. 
Anyone can help with that? 

Ty in advance :)  
 
Hi there, 

I have an issue : 
I had a DML statement inside my constructor and my code worked just fine when trying to test cases by myself. But when i tried to login as another user i discovered my huge mistake, and tried to correct it. Unfortunately, I'm not successful. So that's why i need help to figure out the best way to achieve this : 

Here is MyVFP :
<apex:page controller="OC_CreationDeclarationEquipements"  sidebar="false" tabStyle="OC_FormulaireDeclaEquip__c">
    <style type="text/css">
        .noEquip {
          text-align: center;
          font-weight: bold;
          font-size: 20px;
        }
        
        .MyBtn{
            text-decoration:none;
            padding:4px;
        }
        
        .customPopup {
            background-color: white;
            border-style: solid;
            border-width: 2px;
            left: 20%;
            padding: 10px;
            position: absolute;
            z-index: 9999;
            width: 500px;
            top: 20%;
        }
        
        .popupBackground{
            background-color:black;
            opacity: 0.20;
            filter: alpha(opacity = 20);
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            z-index: 9998;
        }
        
        .imgclass:hover{   
            background-image: url(/img/help/helpOrbs.gif);   
            background-repeat: no-repeat;   
            width: 16px;   
            height: 15px;      
            background-position: right;   
          
        }  
        
        .imgclass{   
            background-image: url(/img/help/helpOrbs.gif);   
            background-repeat: no-repeat;   
            width: 16px;   
            height: 15px;   
        }  
        
        .closeButton {
            float: right;
        }
        
        h1 {
          font-size: 24px;
          text-shadow: -1px -1px #eee, 1px 1px #888, -3px 0 4px #000;
          color:black;
          padding:16px;
          font-weight:lighter;
          text-align:center;
          display:inline;
          line-height:92px;
        }
        
        .innerText {
            font-size: 18px;
            padding:16px;
            margin-right:16px;
        }
    </style>  
        
         

        <apex:pageMessages id="msg"></apex:pageMessages>
        <apex:pageBlock id="newDeclaration" title="Création d'une déclaration d'équipement"  rendered="{!declarationMere.TECH_IsSubmitted__c == false}">
            
                <apex:pageBlockButtons >
                    <apex:form >
                        <apex:commandButton action="{!validate}" value="Valider ma déclaration" rendered="{!haveEquip}" style="padding:6px;"/>
                    </apex:form>
                </apex:pageBlockButtons>
                            
            <!-- Current User Infos 1rst Co-->
            <apex:pageBlockSection collapsible="false" columns="2" rendered="{!haveDeclaration ==false}">
                <apex:outputText value="{!nouvelleDeclaration.Nom__c}" label="Nom Complet"/>
                <apex:outputText value=" {!nouvelleDeclaration.DateDeclaration__c}" label="Date de la déclaration"></apex:outputText>
                <apex:outputText value=" {!nouvelleDeclaration.Matricule__c}" label="Matricule"></apex:outputText>
                <apex:outputText value=" {!nouvelleDeclaration.CodeUnite__c}" label="Code unité"></apex:outputText>
                <apex:outputText value=" {!nouvelleDeclaration.NomManager__c}" label="Responsable"></apex:outputText>
                <apex:outputText value=" {!nouvelleDeclaration.LibelleUnite__c}" label="Libellé unité"></apex:outputText>
                <apex:outputText value=" {!nouvelleDeclaration.MatriculeManager__c}" rendered="true"></apex:outputText>
                <apex:outputText value=" {!nouvelleDeclaration.Responsable__c}" rendered="false" ></apex:outputText>
            </apex:pageBlockSection>
            
            <!-- Current User Infos - Existing declaration -->
            <apex:pageBlockSection collapsible="false" columns="2" rendered="{!haveDeclaration==true}">
                <apex:outputText value="{!declarationMere.Nom__c}" label="Nom Complet"/>
                <apex:outputText value=" {!declarationMere.DateDeclaration__c}" label="Date de la déclaration"></apex:outputText>
                <apex:outputText value=" {!declarationMere.Matricule__c}" label="Matricule"></apex:outputText>
                <apex:outputText value=" {!declarationMere.CodeUnite__c}" label="Code unité"></apex:outputText>
                <apex:outputText value=" {!declarationMere.NomManager__c}" label="Responsable"></apex:outputText>
                <apex:outputText value=" {!declarationMere.LibelleUnite__c}" label="Libellé unité"></apex:outputText>
                <apex:outputText value=" {!declarationMere.MatriculeManager__c}" rendered="false"></apex:outputText>
                <apex:outputText value=" {!declarationMere.Responsable__c}" rendered="false" ></apex:outputText>
            </apex:pageBlockSection>
            
            <!-- Equipements Ajout -->
            <apex:form >
               
            
            <apex:pageBlockSection id="newEquip" title="Ajout d'un équipement" columns="1" >                
                <apex:pageBlockSection >
                    <apex:pageblockSectionItem >
                    <apex:outputLabel value="Type d'équipement" for="equipType"></apex:outputLabel>
                    <apex:actionRegion >
                        <apex:inputField value="{!newEquipement.TypeEquipement__c}" label="Type d'équipement" required="{!requiredType}" id="equipType" >
                            <apex:actionSupport event="onchange" action="{!onChangeValue}" rerender="op1, msg"/> 
                        </apex:inputField>
                    </apex:actionRegion>
                    </apex:pageblockSectionItem>
                </apex:pageBlockSection>

                <apex:pageBlockSection id="op1">
                        <apex:pageBlockSectionItem rendered="{!renderOP2}">
                            <apex:outputPanel >
                                <apex:outputLabel value="{!$ObjectType.OC_Equipement__c.fields.NumeroSerie__c.label}" />
                                <apex:commandButton id="showSerialNumber" image="/img/func_icons/util/help16.png" style="width:5%;padding:0; border:0px;" rerender="popUpSerialNumber" action="{!showPopup}" immediate="true"/>
                            </apex:outputPanel>
                            <apex:inputField id="serialNumber" label="Numéro de série" value="{!newEquipement.NumeroSerie__c}"  required="{!requiredOP2}"></apex:inputField>
                        </apex:pageBlockSectionItem>
                    
                        <apex:inputField id="phoneNumber" label="Numéro de téléphone" value="{!newEquipement.NumeroTelephone__c}" rendered="{!renderOP3}" required="{!requiredOP3}"></apex:inputField>   
                    
                        <apex:pageBlockSectionItem rendered="{!renderOP3}">
                            <apex:outputPanel >
                                <apex:outputLabel value="{!$ObjectType.OC_Equipement__c.fields.NumeroIMEIiPhone__c.label}" />
                                <apex:commandButton id="showImei" image="/img/func_icons/util/help16.png" style="width:5%;padding:0; border:0px;" rerender="popUpIMEI" action="{!showPopup}" immediate="true"/>
                            </apex:outputPanel>
                            <apex:inputField id="imeiNumber" label="Numéro IMEI" value="{!newEquipement.NumeroIMEIiPhone__c}" required="{!requiredOP3}"></apex:inputField>
                        </apex:pageBlockSectionItem>
                        
                        <apex:pageBlockSectionItem rendered="{!renderOP4}">
                            <apex:outputPanel >
                                <apex:outputLabel value="{!$ObjectType.OC_Equipement__c.fields.NumeroSIL__c.label}" />
                                <apex:commandButton id="showSIL" image="/img/func_icons/util/help16.png" style="width:5%;padding:0; border:0px;" rerender="popUpNoSIL" action="{!showPopup}" immediate="true"/>
                            </apex:outputPanel>
                            <apex:inputField id="SILNumber" label="Numéro SIL" value="{!newEquipement.NumeroSIL__c}" required="{!requiredOP4}"></apex:inputField>
                        </apex:pageBlockSectionItem>
                        
                </apex:pageBlockSection>  
                <apex:outputText value="{!newEquipement.DateCreation__c}" rendered="false"></apex:outputText>       
            </apex:pageBlockSection>
             
                
            <!-- POPUP D'AIDE pour le NO SIL-->
            <apex:outputPanel id="popUpNoSIL" title="Où trouver le Numéro SIL ?">
                <apex:outputPanel styleClass="popupBackground" layout="block" rendered="{!displayPopUp}"/>
                    <apex:outputPanel styleClass="customPopup" layout="block" rendered="{!displayPopUp}">
                        <apex:commandButton value="X" title="Fermer la fenêtre" action="{!closePopup}" styleClass="closeButton" rerender="popUpNoSIL" immediate="true"> </apex:commandButton><br/>
                        <h1>
                            Où trouver le numéro SIL ?
                        </h1>
                        <apex:outputPanel styleClass="innerText" layout="block">Merci d'indiquer le numéro sur 7 chiffres mentionné après les caractères SIL sur l’autocollant, comme sur la photo suivante :</apex:outputPanel>
                        <br/>
                        <apex:image id="imageSIL" value="{!$Resource.OC_HelpSIL}" style="width:100%;" />
                        <br/><br/><br/>
                        <apex:commandButton value="Compris !" action="{!closePopup}" rerender="popUpNoSIL" immediate="true" style="margin-left: 45%; padding:6px;"/>
                    </apex:outputPanel>
            </apex:outputPanel>
            
            <!-- POPUP D'AIDE pour le NO de série  -->
            <apex:outputPanel id="popUpSerialNumber">
                <apex:outputPanel styleClass="popupBackground" layout="block" rendered="{!displayPopUp}"/>
                    <apex:outputPanel styleClass="customPopup" layout="block" rendered="{!displayPopUp}">
                        <apex:commandButton value="X" title="Fermer la fenêtre" action="{!closePopup}" styleClass="closeButton" rerender="popUpSerialNumber" immediate="true"> </apex:commandButton><br/>
                        <h1>
                            Où trouver le numéro de série ?
                        </h1><br/>
                        <apex:outputPanel styleClass="innerText" layout="block"> Merci d'indiquer le numéro de série figurant sur l’autocollant, comme sur la photo suivante : </apex:outputPanel>  <br/><br/>
                        <apex:image id="imageSerialNumber" value="{!$Resource.OC_HelpSerialNumber}" style="width:100%;" />
                        <br/><br/><br/>
                        <apex:commandLink styleClass="btn" value="Compris !" action="{!closePopup}" rerender="popUpSerialNumber" immediate="true" style="margin-left: 45%; padding:6px; text-decoration: none;background-color:lightblue;"/>
                    </apex:outputPanel>
            </apex:outputPanel>
            
            <!-- POPUP D'AIDE pour le NO IMEI -->
            <apex:outputPanel id="popUpIMEI" >
                <apex:outputPanel styleClass="popupBackground" layout="block" rendered="{!displayPopUp}"/>
                    <apex:outputPanel styleClass="customPopup" layout="block" rendered="{!displayPopUp}">
                        <apex:commandButton value="X" title="Fermer la fenêtre" action="{!closePopup}" styleClass="closeButton" rerender="popUpIMEI" immediate="true"> </apex:commandButton><br/>
                        <h1 >
                            Où trouver le numéro IMEI ?
                        </h1><br/>
                        <apex:outputPanel styleClass="innerText" layout="block"> Afin de trouver le numéro IMEI de votre appareil, rendez-vous dans : <br/> Réglages > Général > Informations <br/> Descendez un peu plus pas sur la page et saississez le numéro IMEI comme sur la photo ci-après : </apex:outputPanel>  <br/><br/>
                        <apex:image id="imageIMEI" value="{!$Resource.OC_HelpIMEI}" style="width:100%;" />
                        <br/><br/><br/>
                        <apex:commandButton value="Compris !" action="{!closePopup}" rerender="popUpIMEI" immediate="true" style="margin-left: 45%; padding:6px;"/>
                    </apex:outputPanel>
            </apex:outputPanel>
                
                <div style="align:center;"> 
                    <apex:commandButton id="BtnAddEquip" value="Ajouter l'équipement" action="{!save}" status="AddEquip" style="padding:6px;"/>
                </div>
            </apex:form>
            
            <!-- Equipements Consultation -->
            <apex:form >
            <apex:pageBlockSection title="Équipements détenus" collapsible="false" columns="1">
                 <apex:pageblockTable value="{!listEquipementsEnft}" var="equipements" rendered="{!haveEquip == true}">              
                        <apex:column value="{!equipements.TypeEquipement__c}" headerValue="Type d'équipement"></apex:column>        
                        <apex:column value="{!equipements.NumeroSIL__c}" headerValue="Numéro SIL"></apex:column>
                        <apex:column value="{!equipements.NumeroSerie__c}" headerValue="Numéro de série"></apex:column> 
                        <apex:column value="{!equipements.NumeroIMEIiPhone__c}" headerValue="Numéro IMEI"/>  
                        <apex:column value="{!equipements.NumeroTelephone__c}" headerValue="Numéro de téléphone" />  
                        <apex:column value="{!equipements.DateCreation__c}" headerValue="Date de création"></apex:column> 
                        <apex:column headerValue="Actions" >
                            <apex:commandLink styleClass="btn MyBtn" value=" Modifier" onclick="return openPopup('/apex/OC_EditEquipement?id={!equipements.id}');" /> 
                            <apex:commandLink styleClass="btn MyBtn"  value=" Supprimer" action="{!deleteRecord}" onclick="if(!confirm('Êtes-vous sûr(e) de  vouloir supprimer cet équipement ?')) return false;">
                                <apex:param name="equipmentId" value="{!equipements.id}" assignTo="{!selectedEquipement}"/>
                            </apex:commandLink>
                        </apex:column>          
                 </apex:pageblockTable>
                
                <apex:pageBlockSectionItem rendered="{!haveEquip == false}">
                    <div class="noEquip">Vous n'avez pas encore ajouté d'équipement
                    </div>
                </apex:pageBlockSectionItem>
             </apex:pageBlockSection> 
            </apex:form>
      </apex:pageBlock>
    
      <apex:pageBlock id="consultDeclaration" title="Consultation de votre déclaration d'équipement" rendered="{!declarationMere.TECH_IsSubmitted__c == true}">
          
            <!-- Current User Infos - Existing declaration -->
            <apex:pageBlockSection collapsible="false" columns="2" rendered="{!haveDeclaration}">
                <apex:outputText value="{!declarationMere.Nom__c}" label="Nom Complet"/>
                <apex:outputText value=" {!declarationMere.DateDeclaration__c}" label="Date de la déclaration"></apex:outputText>
                <apex:outputText value=" {!declarationMere.Matricule__c}" label="Matricule"></apex:outputText>
                <apex:outputText value=" {!declarationMere.CodeUnite__c}" label="Code unité"></apex:outputText>
                <apex:outputText value=" {!declarationMere.NomManager__c}" label="Responsable"></apex:outputText>
                <apex:outputText value=" {!declarationMere.LibelleUnite__c}" label="Libellé unité"></apex:outputText>
                <apex:outputText value=" {!declarationMere.MatriculeManager__c}" rendered="false"></apex:outputText>
                <apex:outputText value=" {!declarationMere.Responsable__c}" rendered="false" ></apex:outputText>
            </apex:pageBlockSection>

            <!-- Equipements Consultation -->
                <apex:pageBlockSection title="Équipements détenus" collapsible="false" columns="1">
                     <apex:pageblockTable value="{!listEquipementsEnft}" var="equipements" rendered="{!haveEquip == true}">              
                            <apex:column value="{!equipements.TypeEquipement__c}" headerValue="Type d'équipement"></apex:column>        
                            <apex:column value="{!equipements.NumeroSIL__c}" headerValue="Numéro SIL"></apex:column>
                            <apex:column value="{!equipements.NumeroSerie__c}" headerValue="Numéro de série"></apex:column> 
                            <apex:column value="{!equipements.NumeroIMEIiPhone__c}" headerValue="Numéro IMEI"/>  
                            <apex:column value="{!equipements.NumeroTelephone__c}" headerValue="Numéro de téléphone" />  
                            <apex:column value="{!equipements.DateCreation__c}" headerValue="Date de création"></apex:column>       
                     </apex:pageblockTable>
                </apex:pageBlockSection> 
      </apex:pageBlock>
</apex:page>

Here is my controller : 
public class OC_CreationDeclarationEquipements {
    //INFOS USER & Equipement
    public User declarant {get; set;}
    Public Boolean haveDeclaration {get; set;}
    Public Boolean haveEquip {get; set;}
    public OC_FormulaireDeclaEquip__c nouvelleDeclaration {get;set;}
    public OC_Equipement__c newEquipement {get;set;}
    public list<OC_Equipement__c> listEquipementsEnft{get;set;}
    public User manager {get; set;}
    public string selectedEquipement { get; set; }
    public OC_FormulaireDeclaEquip__c declarationMere{get;set;}
    public String selectedRT{get;set;} // selected value of type picklist
    public boolean renderOP2 {get; set;}// true -> show op2
    public boolean renderOP3 {get; set;}// true -> show op3
    public boolean renderOP4 {get; set;}// true -> show op4
    public boolean requiredOP2{get;set;} // true -> field in op2 is required
    public boolean requiredOP3{get;set;}// true -> fields in op3 are required
    public boolean requiredOP4{get;set;}// true -> field in op4 is required
    public boolean requiredType {get; set;}
    public boolean displayPopup{get; set;} // true => Shop popup
    public boolean exectuteDML {get; set;}
    
    
    //Constructeur
    Public OC_CreationDeclarationEquipements() {
        //Set EquipementType field to mandatory
        requiredType = true;
        
        //Search for current user Informations
        declarant = [Select ID, Name, EmployeeNumber, Email, Matricule_responsable__c,Matricule__c,Entit_niveau_304045__c, Libel_Entit_304045__c from USER where id=:UserInfo.getUserId()];
        System.debug('<====== declarant value = '+ declarant +'=======>');
        
        //search his manager        
        manager = [Select Id, Name, Matricule__c from User where Matricule__c = :declarant.Matricule_responsable__c];
        System.debug('<====== manager value = '+manager+'=======>');
        
        //this list is null
        List<OC_FormulaireDeclaEquip__c > lst = [SELECT Id, CreatedById,User__c
                                                 FROM OC_FormulaireDeclaEquip__c 
                                                 WHERE User__c = :Userinfo.getUserId() ];
        System.debug('<====== lst value = '+lst+'=======>');
        
        If (lst.size()>0){
         	haveDeclaration = true;
            // Query objet parent
            nouvelleDeclaration = new OC_FormulaireDeclaEquip__c();
            nouvelleDeclaration = [SELECT  Id,
                                       Name,
                                       Nom__c,
                                       Email__c,
                                       Matricule__c,
                                       MatriculeManager__c,
                                       Commentaire__c,
                                       Responsable__c,
                                       DateDeclaration__c,
                                       NomManager__c,
                               		   CodeUnite__c,
                                	   LibelleUnite__c,
                               		   User__c,
                               		   TECH_IsSubmitted__c
                   FROM OC_FormulaireDeclaEquip__c
                   WHERE User__c =:Userinfo.getUserId() OR Matricule__c =:declarant.Matricule__c limit 1];           
        } else {
            haveDeclaration = false;
            //instanciation de la déclaration si l'utilisateur courant n'a pas encore créé la sienne (toute première ouverture de l'objet)
        	nouvelleDeclaration = new OC_FormulaireDeclaEquip__c (Responsable__c = manager.Id,NomManager__c = manager.Name,CodeUnite__c = declarant.Entit_niveau_304045__c,LibelleUnite__c = declarant.Libel_Entit_304045__c,DateDeclaration__c = System.Now(), Nom__c = declarant.Name, Email__c = declarant.Email, MatriculeManager__c = declarant.Matricule_responsable__c, Matricule__c = declarant.Matricule__c);
       		System.debug('<====== haveDeclaration value = '+haveDeclaration+'=======>');
        }
      	
		//Instanciation équipement        
        newEquipement = new OC_Equipement__c(DateCreation__c = System.Now());

        // Query objet enfant
        listEquipementsEnft = new list<OC_Equipement__c> ();
        listEquipementsEnft = [SELECT ID,
                                      Name,
                                      NumeroTelephone__c,
                               		  NumeroSIL__c,
                                      TypeEquipement__c,
                                      NumeroSerie__c,
                                      NumeroIMEIiPhone__c,
                                      DateCreation__c
                               FROM OC_Equipement__c
                               WHERE DeclarationEquipement__r.User__c =:UserInfo.getUserId()];
        
        if(listEquipementsEnft.size()>0) {
            haveEquip = true;
        } else {
            haveEquip = false;
        }
    }
    
    
    
    public Pagereference save() {
        
        List<OC_Equipement__c> insertEquip = new List<OC_Equipement__c>();  
        System.debug('<====== haveDeclaration value = '+haveDeclaration+'=======>');
        if(haveDeclaration == false) {
            System.debug('<====== nouvelleDeclaration value = '+nouvelleDeclaration+'=======>');
            insert nouvelleDeclaration;
        }
        
            //Création des enregistrements d'équipements rattachés à la déclaration + redirection vers page de réca
            newEquipement.DeclarationEquipement__c = nouvelleDeclaration.ID;
        	System.debug('<====== insertedDeclaration id value = '+nouvelleDeclaration+'=======>');
        	System.debug('<====== newEquip value filled with parentId = '+newEquipement.DeclarationEquipement__c+'=======>');
        	
            insert newEquipement;
        	System.debug('<====== newEquipement inserted value = '+newEquipement+'=======>');
            PageReference pr = new PageReference('/apex/OC_CreationDeclarationEquipements');
        	pr.setRedirect(true);
            return pr;
    }
    
    public Pagereference validate() {
            //Mise à jour de la déclaration afin qu'elle ne soit plus modifiable en cochant le champ TECH_IsSubmitted__c 
            nouvelleDeclaration.TECH_IsSubmitted__c = true;
        	System.debug('<====== declarationMere value = '+declarationMere+'=======>');
        	System.debug('<====== nouvelleDeclaration value = '+nouvelleDeclaration+'=======>');
            update nouvelleDeclaration;
            PageReference pr = new PageReference('/apex/OC_CreationDeclarationEquipements');
        	pr.setRedirect(true);
            return pr;
    }
    
     public PageReference deleteRecord() {
        selectedEquipement = ApexPages.CurrentPage().getParameters().get('equipmentId');
        System.debug('<====== selectedEquipement value = '+selectedEquipement+'=======>');
        OC_Equipement__c deleteRcd = [SELECT Id from OC_Equipement__c where Id = :selectedEquipement limit 1 ];
        System.debug('<====== deleteRcd = ' + deleteRcd + '=======>');

            try{
                delete deleteRcd;
            }
            catch(DmlException ex){
                ApexPages.addMessages(ex);
            }
        
               
        PageReference pr = new PageReference('/apex/OC_CreationDeclarationEquipements');
        pr.setRedirect(true);
        return pr;
    }
    
    //Check value selected on field type equipment to render spécific fields
    public void onChangeValue(){
        selectedRT = newEquipement.TypeEquipement__c;
        
        switch on selectedRT {
   			when '' { 
                renderOP2 = false;
                requiredOP2=false;
                
                renderOP3 = false;
                requiredOP3 = false;
                
                renderOP4 = false;
                requiredOP4 =false;
   			}
   			when 'iPhone', 'iPad' {
       			renderOP2 = false;
                requiredOP2=false;
                
                renderOP3 = true;
                requiredOP3=true;
                
                renderOP4 = false;
                requiredOP4=false;
   			}
            when 'Copieur Multifonctions','Imprimante' { 
                renderOP2 = true;
                requiredOP2 = true;
                
                renderOP3 = false;
                requiredOP3 = false;
                
                renderOP4 = false;
                requiredOP4 = false;
   			}
   			when else {
       			renderOP2 = false;
                requiredOP2 = false;
                
                renderOP3 = false;
                requiredOP3 = false;
                
                renderOP4 = true;
                requiredOP4 = true;
   			}
		}
    }
    
    //Custom PopUp for Help Texts
    public void closePopup() {        
        displayPopup = false;    
    }   
    
    public void showPopup() {        
        displayPopup = true;    
    }
}

What I want to do here is : 

When an user first click on the object Tab, a declaration is inserted (Only one declaration by user is allowed). => right now my issue is there.

Ty in advance for your help 
Amber
Hello there, 

Here is my request :
I have a VFP that looks like below image. 
Actual PageI would like to add a button (easy part), that will allow the current user to add a new equipment line that he owns (corresponding to a new apex:pageblock or apex:pageblocksection), directly on this page ? 
The tricky poing is that each block item will create a new object if all fields are completed upon saving.

Can someone help me achieve this? 
I haven't been able to find anything on that topic :(. 

In advance, Ty very much for your time and anwsers.
Amber 
Hi there, 

I would like to have some advices regarding technical feasibility  of a need and its various possibilities. 

Currently, we have a multi-select list that has no dependency and no limit with 7 items in it.

Now we want to be able to choose items and also say the quantity for each items selected.
User-added image

Creating 7 other number type fields won't be a best practice and will for sure burden the page layout. Plus it will probably be confusing for users. 

I'm now thinking of replacing this multi-select list by a new custom object with the same name : 
 - Record Name (standard field) with type auto-number
 - A picklist field called "Type of animal" with the same values as the previous multi-select list
 - A number field  "Number of animals" that will allows us to fill the quantity 

In addition to this, in the related list of Leads, i'll only show 2 fields Type of  animal & Number of animals. It will still be editable if needed or also deleted if it's no longer the case for the selected lead. 

This method will allow us to keep a light layout on lead and also do the required reporting when needed. 

I would like to know : 
1- Is there a better way to achieve this without adding a new custom object ? 
2- Is this a best practice, considering creating tiny object for one purpose ?
3- I also need to Consider the fact that i'll have to update all existing records that have existing values in this multiselect list to match this evolution and of course number field will have a null value. 

Here is the related list on lead with the new object :
User-added image
Hi there, 

I'm quite stuck here. 
I've written a test class for my batch but it doesn't appears to be running. It stays at 0% :( 

I'm missing something but don't know what. 

Can someone help me figure it out? 

Here is my batch class : 
global class BatchUpdateAllLeads implements Database.Batchable <SObject> {
//START METHOD
    global Database.QueryLocator start(Database.BatchableContext bc){
        String Query='Select id,TECH_Update__c from Lead where TECH_Update__c=false AND Converted=false ' ;
        return Database.getQueryLocator(Query);
            }
//EXECUTE METHOD
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        for(Lead l: scope){
            l.TECH_Update__c = true;
        }
        update scope;
    }
//FINISH METHOD
    global void finish(Database.BatchableContext bc){
        Id job= bc.getJobId();
        System.debug(job);
    }
}

And this is my attemp of writting a proper test class :( 
@istest
private class BatchUpdateAllLeads_TEST {
    @istest
    static void testAcc(){
        List<Lead> l = new List<Lead>();
        Lead l1 = new Lead(Company	='BTP',LastName = 'Test',SIRET__c='12659991955626',Numero_d_ordre__c='9999-99-99',Region_GRDF__c='Ile de France',Tech_Update__c=false,IsConverted=false);
        l.add(l1);

        Lead l2= new Lead(Company	='Comp',LastName = 'Test2',SIRET__c='12659991955687',Numero_d_ordre__c='1111-99-99',Region_GRDF__c='Ile de France',Tech_Update__c=false, IsConverted=true);
        l.add(l2);

        Lead l3= new Lead(Company	='Agny', LastName = 'Test3', SIRET__c='19959991988687', Numero_d_ordre__c='1111-99-11', Region_GRDF__c='Ile de France', Tech_Update__c=true,IsConverted=true);
        l.add(l3);
        insert l;
   
    Test.startTest();
    BatchUpdateAllLeads ap= new BatchUpdateAllLeads();
    Id jobid= Database.executeBatch(ap);
    Test.stopTest();
    }
}

Ty very much for your help
Hi there, I have written a Test Class for a Switch condition but When I'm executing Tests, I still have a 68% Coverage, nothing more. 

Here is my main class wich is tested until case : 33 
public with sharing class UpdateDepartmentField_CLASS {
    public static void UpdateDepartmentFieldCommune(List<Commune__c> communeList) {

        for (Integer i=0;  i < communeList.size(); i++) {
                switch on communeList[i].CodeDepartement__c {
                    when '01' {
                        communeList[i].Departement__c = '01 AIN';
                    }
                    when '02' {
                        communeList[i].Departement__c = '02 AISNE';
                    }
                    when '03' {
                        communeList[i].Departement__c = '03 ALLIER';
                    }
                    when '04' {
                        communeList[i].Departement__c = '04 ALPES-DE-HAUTE-PROVENCE';
                    }
                    when '05' {
                        communeList[i].Departement__c = '05 HAUTES-ALPES';
                    }
                    when '06' {
                        communeList[i].Departement__c = '06 ALPES-MARITIMES';
                    }
                    when '07' {
                        communeList[i].Departement__c = '07 ARDECHE';
                    }
                    when '08' {
                        communeList[i].Departement__c = '08 ARDENNES';
                    }
                    when '09' {
                        communeList[i].Departement__c = '09 ARIEGE';
                    }
                    when '10' {
                        communeList[i].Departement__c = '10 AUBE';
                    }
                    when '11' {
                        communeList[i].Departement__c = '11 AUDE';
                    }
                    when '12' {
                        communeList[i].Departement__c = '12 AVEYRON';
                    }
                    when '13' {
                        communeList[i].Departement__c = '13 BOUCHES-DU-RHONE';
                    }
                    when '14' {
                        communeList[i].Departement__c = '14 CALVADOS';
                    }
                    when '15' {
                        communeList[i].Departement__c = '15 CANTAL';
                    }
                    when '16' {
                        communeList[i].Departement__c = '16 CHARENTE';
                    }
                    when '17' {
                        communeList[i].Departement__c = '17 CHARENTE-MARITIME';
                    }
                    when '18' {
                        communeList[i].Departement__c = '18 CHER';
                    }
                    when '19' {
                        communeList[i].Departement__c = '19 CORREZE';
                    }
                    when '21' {
                        communeList[i].Departement__c = '21 COTE-D\'OR';
                    }
                    when '22' {
                        communeList[i].Departement__c = '22 COTES-D\'ARMOR';
                    }
                    when '23' {
                        communeList[i].Departement__c = '23 CREUSE';
                    }
                    when '24' {
                        communeList[i].Departement__c = '24 DORDOGNE';
                    }
                    when '25' {
                        communeList[i].Departement__c = '25 DOUBS';
                    }
                    when '26' {
                        communeList[i].Departement__c = '26 DROME';
                    }
                    when '27' {
                        communeList[i].Departement__c = '27 EURE';
                    }
                    when '28' {
                        communeList[i].Departement__c = '28 EURE-ET-LOIR';
                    }
                    when '29' {
                        communeList[i].Departement__c = '29 FINISTERE';
                    }
                    when '30' {
                        communeList[i].Departement__c = '30 GARD';
                    }
                    when '31' {
                        communeList[i].Departement__c = '31 HAUTE-GARONNE';
                    }
                    when '32' {
                        communeList[i].Departement__c = '32 GERS';
                    }
                    when '33' {
                        communeList[i].Departement__c = '33 GIRONDE';
                    }
                    when '34' {
                        communeList[i].Departement__c = '34 HERAULT';
                    }
                    when '35' {
                        communeList[i].Departement__c = '35 ILLE-ET-VILAINE';
                    }
                    when '36' {
                        communeList[i].Departement__c = '36 INDRE';
                    }
                    when '37' {
                        communeList[i].Departement__c = '37 INDRE-ET-LOIRE';
                    }
                    when '38' {
                        communeList[i].Departement__c = '38 ISERE';
                    }
                    when '39' {
                        communeList[i].Departement__c = '39 JURA';
                    }
                    when '40' {
                        communeList[i].Departement__c = '40 LANDES';
                    }
                    when '41' {
                        communeList[i].Departement__c = '41 LOIR-ET-CHER';
                    }
                    when '42' {
                        communeList[i].Departement__c = '42 LOIRE';
                    }
                    when '43' {
                        communeList[i].Departement__c = '43 HAUTE-LOIRE';
                    }
                    when '44' {
                        communeList[i].Departement__c = '44 LOIRE-ATLANTIQUE';
                    }
                    when '45' {
                        communeList[i].Departement__c = '45 LOIRET';
                    }
                    when '46' {
                        communeList[i].Departement__c = '46 LOT';
                    }
                    when '47' {
                        communeList[i].Departement__c = '47 LOT-ET-GARONNE';
                    }
                    when '48' {
                        communeList[i].Departement__c = '48 LOZERE';
                    }
                    when '49' {
                        communeList[i].Departement__c = '49 MAINE-ET-LOIRE';
                    }
                    when '50' {
                        communeList[i].Departement__c = '50 MANCHE';
                    }
                    when '51' {
                        communeList[i].Departement__c = '51 MARNE';
                    }
                    when '52' {
                        communeList[i].Departement__c = '52 HAUTE-MARNE';
                    }
                    when '53' {
                        communeList[i].Departement__c = '53 MAYENNE';
                    }
                    when '54' {
                        communeList[i].Departement__c = '54 MEURTHE-ET-MOSELLE';
                    }
                    when '55' {
                        communeList[i].Departement__c = '55 MEUSE';
                    }
                    when '56' {
                        communeList[i].Departement__c = '56 MORBIHAN';
                    }
                    when '57' {
                        communeList[i].Departement__c = '57 MOSELLE';
                    }
                    when '58' {
                        communeList[i].Departement__c = '58 NIEVRE';
                    }
                    when '59' {
                        communeList[i].Departement__c = '59 NORD';
                    }
                    when '60' {
                        communeList[i].Departement__c = '60 OISE';
                    }
                    when '61' {
                        communeList[i].Departement__c = '61 ORNE';
                    }
                    when '62' {
                        communeList[i].Departement__c = '62 PAS-DE-CALAIS';
                    }
                    when '63' {
                        communeList[i].Departement__c = '63 PUY-DE-DOME';
                    }
                    when '64' {
                        communeList[i].Departement__c = '64 PYRENEES-ATLANTIQUES';
                    }
                    when '65' {
                        communeList[i].Departement__c = '65 HAUTES-PYRENEES';
                    }
                    when '66' {
                        communeList[i].Departement__c = '66 PYRENEES-ORIENTALES';
                    }
                    when '67' {
                        communeList[i].Departement__c = '67 BAS-RHIN';
                    }
                    when '68' {
                        communeList[i].Departement__c = '68 HAUT-RHIN';
                    }
                        when '69' {
                            communeList[i].Departement__c = '69 RHONE';
                        }
                        when '70' {
                            communeList[i].Departement__c = '70 HAUTE-SAONE';
                        }
                        when '71' {
                            communeList[i].Departement__c = '71 SAONE-ET-LOIRE';
                        }
                        when '72' {
                            communeList[i].Departement__c = '72 SARTHE';
                        }
                        when '73' {
                            communeList[i].Departement__c = '73 SAVOIE';
                        }
                        when '74' {
                            communeList[i].Departement__c = '74 HAUTE-SAVOIE';
                        }
                        when '75' {
                            communeList[i].Departement__c = '75 PARIS';
                        }
                        when '76' {
                            communeList[i].Departement__c = '76 SEINE-MARITIME';
                        }
                        when '77' {
                            communeList[i].Departement__c = '77 SEINE-ET-MARNE';
                        }
                        when '78' {
                            communeList[i].Departement__c = '78 YVELINES';
                        }
                        when '79' {
                            communeList[i].Departement__c = '79 DEUX-SEVRES';
                        }
                        when '80' {
                            communeList[i].Departement__c = '80 SOMME';
                        }
                        when '81' {
                            communeList[i].Departement__c = '81 TARN';
                        }
                        when '82' {
                            communeList[i].Departement__c = '82 TARN-ET-GARONNE';
                        }
                        when '83' {
                            communeList[i].Departement__c = '83 VAR';
                        }
                        when '84' {
                            communeList[i].Departement__c = '84 VAUCLUSE';
                        }
                        when '85' {
                            communeList[i].Departement__c = '85 VENDEE';
                        }
                        when '86' {
                            communeList[i].Departement__c = '86 VIENNE';
                        }
                        when '87' {
                            communeList[i].Departement__c = '87 HAUTE-VIENNE';
                        }
                        when '88' {
                            communeList[i].Departement__c = '88 VOSGES';
                        }
                        when '89' {
                            communeList[i].Departement__c = '89 YONNE';
                        }
                        when '90' {
                            communeList[i].Departement__c = '90 TERRITOIRE DE BELFORT';
                        }
                        when '91' {
                            communeList[i].Departement__c = '91 ESSONNE';
                        }
                        when '92' {
                            communeList[i].Departement__c = '92 HAUTS-DE-SEINE';
                        }
                        when '93' {
                            communeList[i].Departement__c = '93 SEINE-SAINT-DENIS';
                        }
                        when '94' {
                            communeList[i].Departement__c = '94 VAL-DE-MARNE';
                        }
                        when '95' {
                            communeList[i].Departement__c = '95 VAL-D\'OISE';
                        }
                        when '2B', '2b' {
                            communeList[i].Departement__c = '2B Haute-Corse ';
                        }
                        when '2A', '2a' {
                            communeList[i].Departement__c = '2A Corse-du-Sud ';
                        }
                        when else {
                            communeList[i].Departement__c = null;
                        }
                    }
                }
            }
 }
I know it's a huge condition so maybe there are some limitations ?

Here is my test class
@isTest
public with sharing class UpdateDepartmentField_TEST {
    @isTest static void TestUpdateDepartmentField() {
        //First I create a commune that should be automatically updated with Department__c
        Commune__c newCommune = new Commune__c();
        newCommune.Name='Commune 1';
        newCommune.CodeInseeCommune__c='12265';
        newCommune.CodeDepartement__c='01';
        newCommune.CodeCanton__c='02';
        newCommune.CodeRegion__c='73';
        insert newCommune;

        //Then i'll update this commune with all dept
        for (Integer i=2; i < 96; i++) {
            if (i<10) {
                newCommune.CodeDepartement__c= '0'+String.valueOf(i);
                update newCommune;
            } else if (i>9 && i<96) {
                newCommune.CodeDepartement__c= String.valueOf(i);
                update newCommune;
            }
        }

        newCommune.CodeDepartement__c='2B';
        update newCommune;

        newCommune.CodeDepartement__c='2A';
        update newCommune;         
    }
}
I don't know what i'm missing here.
When I test manually everithing seems fine, so i think it's only related to the test class. 
Do you see anything that could help reach 100% for this test class ? 

 
Hello, 

I need help Writting a test class since it's the first time i try it for real. I've done trailhead but i don't really see how it can apply to my trigger. 

Can someone can help me correct it and reach at least 75% of coverage code? I'm currently at 59%. 

Here is my Trigger : 
trigger UpdateCommune on Commune__c (before insert, before update) {
    //Store all Canton Codes in newly created records for Commune__c
    List<String> cantonCode = new List<String>();
    
    for (Commune__c a:Trigger.new){
        cantonCode.add(a.CodeCanton4Chiffres__c);
    }

    //Loop to update each Commune__c record with the proper CantonId__c
    List <Canton__C> CantonList = [Select ID, Name, CodeCanton4Chiffres__c from Canton__C where CodeCanton4Chiffres__c in :cantonCode];
    
    for (Integer i = 0; i <Trigger.new.size(); i++){
        if (CantonList.size() > 0 && Trigger.new[i].CodeCanton4Chiffres__c !=null){
            for (Canton__C c:CantonList){
                if (Trigger.new[i].CodeCanton4Chiffres__c == c.CodeCanton4Chiffres__c){
                    Trigger.new[i].CantonId__c = c.ID;
                  }
            }
        }
       else{
       Trigger.new[i].CantonId__c = null;
       System.System.debug('La référence Canton n\' pas pu être trouvée. Mise à jour impossible de la commune ');
        }
        
        // once the commune is updated with Canton ID, we need to update its "RegionAdministrative__c" fields regarding its "RegionCode__c" field value
    switch on Trigger.new[i].CodeRegion__c {
        when '82', '83' {
            Trigger.new[i].RegionAdministrative__c = 'AUVERGNE-RHONE-ALPES';
        }
        when '26', '43' {
            Trigger.new[i].RegionAdministrative__c = 'BOURGOGNE-FRANCHE-COMTE';
        }
        when '53' {
            Trigger.new[i].RegionAdministrative__c = 'BRETAGNE';
        }
        when '24' {
            Trigger.new[i].RegionAdministrative__c = 'CENTRE-VAL DE LOIRE';
        }
        when '94' {
            Trigger.new[i].RegionAdministrative__c = 'CORSE';
        }
        when '21','41', '42' {
            Trigger.new[i].RegionAdministrative__c = 'GRAND EST';
        }
        when '22', '31' {
            Trigger.new[i].RegionAdministrative__c = 'HAUTS-DE-FRANCE';
        }
        when  '11' {
            Trigger.new[i].RegionAdministrative__c = 'ILE-DE-FRANCE';
        }
        when '25', '23' {
            Trigger.new[i].RegionAdministrative__c = 'NORMANDIE';
        }        
        when '54', '74', '72' {
            Trigger.new[i].RegionAdministrative__c = 'NOUVELLE-AQUITAINE';
        }
        when '73', '91' {
            Trigger.new[i].RegionAdministrative__c = 'OCCITANIE';
        }
        when '52' {
            Trigger.new[i].RegionAdministrative__c = 'PAYS DE LA LOIRE';
        }
        when '93' {
            Trigger.new[i].RegionAdministrative__c = 'PROVENCE-ALPES-COTE D\'AZUR';
        }
    }
    }

}

Here is my Test Class : 
@isTest
private with sharing class UpdateCommune_TEST {
    private static testMethod void updateCommuneTEST() {
        // Create 2 Cantons then add them to a list that we will insert in Canton__c
        List<Canton__c> cantonList = new List<Canton__c>();

        Canton__c canton1 = new Canton__c(Name='Test Canton 2', CodeInseeCanton__c='12345', CodeCanton__c='01', CodeDepartement__c='12' );
        cantonList.add(canton1) ;
        Canton__c canton2 = new Canton__c(Name='Test Canton 2',  CodeInseeCanton__c='12543', CodeCanton__c='02', CodeDepartement__c='12' );
        cantonList.add(canton2) ;
        

        // Create 2 cities then add them to a list that we will insert in Commune__c
        List<Commune__c> communeList = new List<Commune__c>();
        Commune__c commune1 = new Commune__c(Name='Commune 1', CodeInseeCommune__c='12264', CodeDepartement__c='12', CodeCanton__c='01', CodeRegion__c='73');
        communeList.add(commune1);
        Commune__c commune2 = new Commune__c(Name='Commune 2', CodeInseeCommune__c='12265', CodeDepartement__c='12', CodeCanton__c='02', CodeRegion__c='73');
        communeList.add(commune2);
        
        test.startTest();
        insert cantonList;
        insert communeList;
        test.stopTest();

        // Retrieve the new communes
        List<Commune__c> createdCommunes = new List<Commune__c>([Select Name, Id, CodeInseeCommune__c, CodeDepartement__c, CodeCanton__c, CodeCanton4Chiffres__c, CodeRegion__c,Departement__c,CantonId__c, RegionAdministrative__c from Commune__c Where  CodeCanton4Chiffres__c='1201' OR CodeCanton4Chiffres__c='1202']);
       
        for (Integer i=0; i < createdCommunes.size(); i++) {
            System.debug('Value of canton after trigger fired: ' + createdCommunes[i].CantonId__c);
            // Test that the trigger correctly updated the RegionAdministrative
            System.assertEquals('OCCITANIE', createdCommunes[i].RegionAdministrative__c);
        }    
    }
}

Ty in advance for your help. 

 
Hi there, 

I'm quite stuck here. 
I've written a test class for my batch but it doesn't appears to be running. It stays at 0% :( 

I'm missing something but don't know what. 

Can someone help me figure it out? 

Here is my batch class : 
global class BatchUpdateAllLeads implements Database.Batchable <SObject> {
//START METHOD
    global Database.QueryLocator start(Database.BatchableContext bc){
        String Query='Select id,TECH_Update__c from Lead where TECH_Update__c=false AND Converted=false ' ;
        return Database.getQueryLocator(Query);
            }
//EXECUTE METHOD
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        for(Lead l: scope){
            l.TECH_Update__c = true;
        }
        update scope;
    }
//FINISH METHOD
    global void finish(Database.BatchableContext bc){
        Id job= bc.getJobId();
        System.debug(job);
    }
}

And this is my attemp of writting a proper test class :( 
@istest
private class BatchUpdateAllLeads_TEST {
    @istest
    static void testAcc(){
        List<Lead> l = new List<Lead>();
        Lead l1 = new Lead(Company	='BTP',LastName = 'Test',SIRET__c='12659991955626',Numero_d_ordre__c='9999-99-99',Region_GRDF__c='Ile de France',Tech_Update__c=false,IsConverted=false);
        l.add(l1);

        Lead l2= new Lead(Company	='Comp',LastName = 'Test2',SIRET__c='12659991955687',Numero_d_ordre__c='1111-99-99',Region_GRDF__c='Ile de France',Tech_Update__c=false, IsConverted=true);
        l.add(l2);

        Lead l3= new Lead(Company	='Agny', LastName = 'Test3', SIRET__c='19959991988687', Numero_d_ordre__c='1111-99-11', Region_GRDF__c='Ile de France', Tech_Update__c=true,IsConverted=true);
        l.add(l3);
        insert l;
   
    Test.startTest();
    BatchUpdateAllLeads ap= new BatchUpdateAllLeads();
    Id jobid= Database.executeBatch(ap);
    Test.stopTest();
    }
}

Ty very much for your help
Hello, 

I have tried to generate a random number that changes any time my function is called using Math.Random. but it appears that the number is still the same in the context, and never change : 
here is what i've done. 

The function : 
public static Integer getRandomNumber(Integer listSize){
        Integer randomNumber = Integer.valueof(Math.random() * listSize);
        System.debug('randomNumber' + randomNumber);
        return randomNumber;
    }

When i call the previous function :
List<trailheadapp__User_Badge__c> recordsToInsert = new List<trailheadapp__User_Badge__c>();
        for(Integer i=0; i<300; i++) {
            String randomString = badgeStatus[getRandomNumber(listSize)];
            String randomBadge = badgeList[getRandomNumberForBadge(listBadgeSize)];
            String randomUserID = idList[getRandomId(listIdSize)];
            System.debug('RANDOM USER ID = '+randomUserID);
            trailheadapp__User_Badge__c newJunctionRecord = new trailheadapp__User_Badge__c (trailheadapp__External_ID__c = '0050E00000823JEQAY-a093X00001SmGRWQA'+i,trailheadapp__Status__c = randomString, trailheadapp__Badge__c = randomBadge, trailheadapp__User__c = randomUserID);
            recordsToInsert.add(newJunctionRecord);
        }
        insert recordsToInsert;
The random number remains the sames for all records inserted, what i want is that number changes for every record. 

Does someone see something wrong ?

Ty in advance for help
Amber
Hi there, 

I'm quite stuck here. 
I've written a test class for my batch but it doesn't appears to be running. It stays at 0% :( 

I'm missing something but don't know what. 

Can someone help me figure it out? 

Here is my batch class : 
global class BatchUpdateAllLeads implements Database.Batchable <SObject> {
//START METHOD
    global Database.QueryLocator start(Database.BatchableContext bc){
        String Query='Select id,TECH_Update__c from Lead where TECH_Update__c=false AND Converted=false ' ;
        return Database.getQueryLocator(Query);
            }
//EXECUTE METHOD
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        for(Lead l: scope){
            l.TECH_Update__c = true;
        }
        update scope;
    }
//FINISH METHOD
    global void finish(Database.BatchableContext bc){
        Id job= bc.getJobId();
        System.debug(job);
    }
}

And this is my attemp of writting a proper test class :( 
@istest
private class BatchUpdateAllLeads_TEST {
    @istest
    static void testAcc(){
        List<Lead> l = new List<Lead>();
        Lead l1 = new Lead(Company	='BTP',LastName = 'Test',SIRET__c='12659991955626',Numero_d_ordre__c='9999-99-99',Region_GRDF__c='Ile de France',Tech_Update__c=false,IsConverted=false);
        l.add(l1);

        Lead l2= new Lead(Company	='Comp',LastName = 'Test2',SIRET__c='12659991955687',Numero_d_ordre__c='1111-99-99',Region_GRDF__c='Ile de France',Tech_Update__c=false, IsConverted=true);
        l.add(l2);

        Lead l3= new Lead(Company	='Agny', LastName = 'Test3', SIRET__c='19959991988687', Numero_d_ordre__c='1111-99-11', Region_GRDF__c='Ile de France', Tech_Update__c=true,IsConverted=true);
        l.add(l3);
        insert l;
   
    Test.startTest();
    BatchUpdateAllLeads ap= new BatchUpdateAllLeads();
    Id jobid= Database.executeBatch(ap);
    Test.stopTest();
    }
}

Ty very much for your help
Hi there, I have written a Test Class for a Switch condition but When I'm executing Tests, I still have a 68% Coverage, nothing more. 

Here is my main class wich is tested until case : 33 
public with sharing class UpdateDepartmentField_CLASS {
    public static void UpdateDepartmentFieldCommune(List<Commune__c> communeList) {

        for (Integer i=0;  i < communeList.size(); i++) {
                switch on communeList[i].CodeDepartement__c {
                    when '01' {
                        communeList[i].Departement__c = '01 AIN';
                    }
                    when '02' {
                        communeList[i].Departement__c = '02 AISNE';
                    }
                    when '03' {
                        communeList[i].Departement__c = '03 ALLIER';
                    }
                    when '04' {
                        communeList[i].Departement__c = '04 ALPES-DE-HAUTE-PROVENCE';
                    }
                    when '05' {
                        communeList[i].Departement__c = '05 HAUTES-ALPES';
                    }
                    when '06' {
                        communeList[i].Departement__c = '06 ALPES-MARITIMES';
                    }
                    when '07' {
                        communeList[i].Departement__c = '07 ARDECHE';
                    }
                    when '08' {
                        communeList[i].Departement__c = '08 ARDENNES';
                    }
                    when '09' {
                        communeList[i].Departement__c = '09 ARIEGE';
                    }
                    when '10' {
                        communeList[i].Departement__c = '10 AUBE';
                    }
                    when '11' {
                        communeList[i].Departement__c = '11 AUDE';
                    }
                    when '12' {
                        communeList[i].Departement__c = '12 AVEYRON';
                    }
                    when '13' {
                        communeList[i].Departement__c = '13 BOUCHES-DU-RHONE';
                    }
                    when '14' {
                        communeList[i].Departement__c = '14 CALVADOS';
                    }
                    when '15' {
                        communeList[i].Departement__c = '15 CANTAL';
                    }
                    when '16' {
                        communeList[i].Departement__c = '16 CHARENTE';
                    }
                    when '17' {
                        communeList[i].Departement__c = '17 CHARENTE-MARITIME';
                    }
                    when '18' {
                        communeList[i].Departement__c = '18 CHER';
                    }
                    when '19' {
                        communeList[i].Departement__c = '19 CORREZE';
                    }
                    when '21' {
                        communeList[i].Departement__c = '21 COTE-D\'OR';
                    }
                    when '22' {
                        communeList[i].Departement__c = '22 COTES-D\'ARMOR';
                    }
                    when '23' {
                        communeList[i].Departement__c = '23 CREUSE';
                    }
                    when '24' {
                        communeList[i].Departement__c = '24 DORDOGNE';
                    }
                    when '25' {
                        communeList[i].Departement__c = '25 DOUBS';
                    }
                    when '26' {
                        communeList[i].Departement__c = '26 DROME';
                    }
                    when '27' {
                        communeList[i].Departement__c = '27 EURE';
                    }
                    when '28' {
                        communeList[i].Departement__c = '28 EURE-ET-LOIR';
                    }
                    when '29' {
                        communeList[i].Departement__c = '29 FINISTERE';
                    }
                    when '30' {
                        communeList[i].Departement__c = '30 GARD';
                    }
                    when '31' {
                        communeList[i].Departement__c = '31 HAUTE-GARONNE';
                    }
                    when '32' {
                        communeList[i].Departement__c = '32 GERS';
                    }
                    when '33' {
                        communeList[i].Departement__c = '33 GIRONDE';
                    }
                    when '34' {
                        communeList[i].Departement__c = '34 HERAULT';
                    }
                    when '35' {
                        communeList[i].Departement__c = '35 ILLE-ET-VILAINE';
                    }
                    when '36' {
                        communeList[i].Departement__c = '36 INDRE';
                    }
                    when '37' {
                        communeList[i].Departement__c = '37 INDRE-ET-LOIRE';
                    }
                    when '38' {
                        communeList[i].Departement__c = '38 ISERE';
                    }
                    when '39' {
                        communeList[i].Departement__c = '39 JURA';
                    }
                    when '40' {
                        communeList[i].Departement__c = '40 LANDES';
                    }
                    when '41' {
                        communeList[i].Departement__c = '41 LOIR-ET-CHER';
                    }
                    when '42' {
                        communeList[i].Departement__c = '42 LOIRE';
                    }
                    when '43' {
                        communeList[i].Departement__c = '43 HAUTE-LOIRE';
                    }
                    when '44' {
                        communeList[i].Departement__c = '44 LOIRE-ATLANTIQUE';
                    }
                    when '45' {
                        communeList[i].Departement__c = '45 LOIRET';
                    }
                    when '46' {
                        communeList[i].Departement__c = '46 LOT';
                    }
                    when '47' {
                        communeList[i].Departement__c = '47 LOT-ET-GARONNE';
                    }
                    when '48' {
                        communeList[i].Departement__c = '48 LOZERE';
                    }
                    when '49' {
                        communeList[i].Departement__c = '49 MAINE-ET-LOIRE';
                    }
                    when '50' {
                        communeList[i].Departement__c = '50 MANCHE';
                    }
                    when '51' {
                        communeList[i].Departement__c = '51 MARNE';
                    }
                    when '52' {
                        communeList[i].Departement__c = '52 HAUTE-MARNE';
                    }
                    when '53' {
                        communeList[i].Departement__c = '53 MAYENNE';
                    }
                    when '54' {
                        communeList[i].Departement__c = '54 MEURTHE-ET-MOSELLE';
                    }
                    when '55' {
                        communeList[i].Departement__c = '55 MEUSE';
                    }
                    when '56' {
                        communeList[i].Departement__c = '56 MORBIHAN';
                    }
                    when '57' {
                        communeList[i].Departement__c = '57 MOSELLE';
                    }
                    when '58' {
                        communeList[i].Departement__c = '58 NIEVRE';
                    }
                    when '59' {
                        communeList[i].Departement__c = '59 NORD';
                    }
                    when '60' {
                        communeList[i].Departement__c = '60 OISE';
                    }
                    when '61' {
                        communeList[i].Departement__c = '61 ORNE';
                    }
                    when '62' {
                        communeList[i].Departement__c = '62 PAS-DE-CALAIS';
                    }
                    when '63' {
                        communeList[i].Departement__c = '63 PUY-DE-DOME';
                    }
                    when '64' {
                        communeList[i].Departement__c = '64 PYRENEES-ATLANTIQUES';
                    }
                    when '65' {
                        communeList[i].Departement__c = '65 HAUTES-PYRENEES';
                    }
                    when '66' {
                        communeList[i].Departement__c = '66 PYRENEES-ORIENTALES';
                    }
                    when '67' {
                        communeList[i].Departement__c = '67 BAS-RHIN';
                    }
                    when '68' {
                        communeList[i].Departement__c = '68 HAUT-RHIN';
                    }
                        when '69' {
                            communeList[i].Departement__c = '69 RHONE';
                        }
                        when '70' {
                            communeList[i].Departement__c = '70 HAUTE-SAONE';
                        }
                        when '71' {
                            communeList[i].Departement__c = '71 SAONE-ET-LOIRE';
                        }
                        when '72' {
                            communeList[i].Departement__c = '72 SARTHE';
                        }
                        when '73' {
                            communeList[i].Departement__c = '73 SAVOIE';
                        }
                        when '74' {
                            communeList[i].Departement__c = '74 HAUTE-SAVOIE';
                        }
                        when '75' {
                            communeList[i].Departement__c = '75 PARIS';
                        }
                        when '76' {
                            communeList[i].Departement__c = '76 SEINE-MARITIME';
                        }
                        when '77' {
                            communeList[i].Departement__c = '77 SEINE-ET-MARNE';
                        }
                        when '78' {
                            communeList[i].Departement__c = '78 YVELINES';
                        }
                        when '79' {
                            communeList[i].Departement__c = '79 DEUX-SEVRES';
                        }
                        when '80' {
                            communeList[i].Departement__c = '80 SOMME';
                        }
                        when '81' {
                            communeList[i].Departement__c = '81 TARN';
                        }
                        when '82' {
                            communeList[i].Departement__c = '82 TARN-ET-GARONNE';
                        }
                        when '83' {
                            communeList[i].Departement__c = '83 VAR';
                        }
                        when '84' {
                            communeList[i].Departement__c = '84 VAUCLUSE';
                        }
                        when '85' {
                            communeList[i].Departement__c = '85 VENDEE';
                        }
                        when '86' {
                            communeList[i].Departement__c = '86 VIENNE';
                        }
                        when '87' {
                            communeList[i].Departement__c = '87 HAUTE-VIENNE';
                        }
                        when '88' {
                            communeList[i].Departement__c = '88 VOSGES';
                        }
                        when '89' {
                            communeList[i].Departement__c = '89 YONNE';
                        }
                        when '90' {
                            communeList[i].Departement__c = '90 TERRITOIRE DE BELFORT';
                        }
                        when '91' {
                            communeList[i].Departement__c = '91 ESSONNE';
                        }
                        when '92' {
                            communeList[i].Departement__c = '92 HAUTS-DE-SEINE';
                        }
                        when '93' {
                            communeList[i].Departement__c = '93 SEINE-SAINT-DENIS';
                        }
                        when '94' {
                            communeList[i].Departement__c = '94 VAL-DE-MARNE';
                        }
                        when '95' {
                            communeList[i].Departement__c = '95 VAL-D\'OISE';
                        }
                        when '2B', '2b' {
                            communeList[i].Departement__c = '2B Haute-Corse ';
                        }
                        when '2A', '2a' {
                            communeList[i].Departement__c = '2A Corse-du-Sud ';
                        }
                        when else {
                            communeList[i].Departement__c = null;
                        }
                    }
                }
            }
 }
I know it's a huge condition so maybe there are some limitations ?

Here is my test class
@isTest
public with sharing class UpdateDepartmentField_TEST {
    @isTest static void TestUpdateDepartmentField() {
        //First I create a commune that should be automatically updated with Department__c
        Commune__c newCommune = new Commune__c();
        newCommune.Name='Commune 1';
        newCommune.CodeInseeCommune__c='12265';
        newCommune.CodeDepartement__c='01';
        newCommune.CodeCanton__c='02';
        newCommune.CodeRegion__c='73';
        insert newCommune;

        //Then i'll update this commune with all dept
        for (Integer i=2; i < 96; i++) {
            if (i<10) {
                newCommune.CodeDepartement__c= '0'+String.valueOf(i);
                update newCommune;
            } else if (i>9 && i<96) {
                newCommune.CodeDepartement__c= String.valueOf(i);
                update newCommune;
            }
        }

        newCommune.CodeDepartement__c='2B';
        update newCommune;

        newCommune.CodeDepartement__c='2A';
        update newCommune;         
    }
}
I don't know what i'm missing here.
When I test manually everithing seems fine, so i think it's only related to the test class. 
Do you see anything that could help reach 100% for this test class ? 

 
Hello, 

I need help Writting a test class since it's the first time i try it for real. I've done trailhead but i don't really see how it can apply to my trigger. 

Can someone can help me correct it and reach at least 75% of coverage code? I'm currently at 59%. 

Here is my Trigger : 
trigger UpdateCommune on Commune__c (before insert, before update) {
    //Store all Canton Codes in newly created records for Commune__c
    List<String> cantonCode = new List<String>();
    
    for (Commune__c a:Trigger.new){
        cantonCode.add(a.CodeCanton4Chiffres__c);
    }

    //Loop to update each Commune__c record with the proper CantonId__c
    List <Canton__C> CantonList = [Select ID, Name, CodeCanton4Chiffres__c from Canton__C where CodeCanton4Chiffres__c in :cantonCode];
    
    for (Integer i = 0; i <Trigger.new.size(); i++){
        if (CantonList.size() > 0 && Trigger.new[i].CodeCanton4Chiffres__c !=null){
            for (Canton__C c:CantonList){
                if (Trigger.new[i].CodeCanton4Chiffres__c == c.CodeCanton4Chiffres__c){
                    Trigger.new[i].CantonId__c = c.ID;
                  }
            }
        }
       else{
       Trigger.new[i].CantonId__c = null;
       System.System.debug('La référence Canton n\' pas pu être trouvée. Mise à jour impossible de la commune ');
        }
        
        // once the commune is updated with Canton ID, we need to update its "RegionAdministrative__c" fields regarding its "RegionCode__c" field value
    switch on Trigger.new[i].CodeRegion__c {
        when '82', '83' {
            Trigger.new[i].RegionAdministrative__c = 'AUVERGNE-RHONE-ALPES';
        }
        when '26', '43' {
            Trigger.new[i].RegionAdministrative__c = 'BOURGOGNE-FRANCHE-COMTE';
        }
        when '53' {
            Trigger.new[i].RegionAdministrative__c = 'BRETAGNE';
        }
        when '24' {
            Trigger.new[i].RegionAdministrative__c = 'CENTRE-VAL DE LOIRE';
        }
        when '94' {
            Trigger.new[i].RegionAdministrative__c = 'CORSE';
        }
        when '21','41', '42' {
            Trigger.new[i].RegionAdministrative__c = 'GRAND EST';
        }
        when '22', '31' {
            Trigger.new[i].RegionAdministrative__c = 'HAUTS-DE-FRANCE';
        }
        when  '11' {
            Trigger.new[i].RegionAdministrative__c = 'ILE-DE-FRANCE';
        }
        when '25', '23' {
            Trigger.new[i].RegionAdministrative__c = 'NORMANDIE';
        }        
        when '54', '74', '72' {
            Trigger.new[i].RegionAdministrative__c = 'NOUVELLE-AQUITAINE';
        }
        when '73', '91' {
            Trigger.new[i].RegionAdministrative__c = 'OCCITANIE';
        }
        when '52' {
            Trigger.new[i].RegionAdministrative__c = 'PAYS DE LA LOIRE';
        }
        when '93' {
            Trigger.new[i].RegionAdministrative__c = 'PROVENCE-ALPES-COTE D\'AZUR';
        }
    }
    }

}

Here is my Test Class : 
@isTest
private with sharing class UpdateCommune_TEST {
    private static testMethod void updateCommuneTEST() {
        // Create 2 Cantons then add them to a list that we will insert in Canton__c
        List<Canton__c> cantonList = new List<Canton__c>();

        Canton__c canton1 = new Canton__c(Name='Test Canton 2', CodeInseeCanton__c='12345', CodeCanton__c='01', CodeDepartement__c='12' );
        cantonList.add(canton1) ;
        Canton__c canton2 = new Canton__c(Name='Test Canton 2',  CodeInseeCanton__c='12543', CodeCanton__c='02', CodeDepartement__c='12' );
        cantonList.add(canton2) ;
        

        // Create 2 cities then add them to a list that we will insert in Commune__c
        List<Commune__c> communeList = new List<Commune__c>();
        Commune__c commune1 = new Commune__c(Name='Commune 1', CodeInseeCommune__c='12264', CodeDepartement__c='12', CodeCanton__c='01', CodeRegion__c='73');
        communeList.add(commune1);
        Commune__c commune2 = new Commune__c(Name='Commune 2', CodeInseeCommune__c='12265', CodeDepartement__c='12', CodeCanton__c='02', CodeRegion__c='73');
        communeList.add(commune2);
        
        test.startTest();
        insert cantonList;
        insert communeList;
        test.stopTest();

        // Retrieve the new communes
        List<Commune__c> createdCommunes = new List<Commune__c>([Select Name, Id, CodeInseeCommune__c, CodeDepartement__c, CodeCanton__c, CodeCanton4Chiffres__c, CodeRegion__c,Departement__c,CantonId__c, RegionAdministrative__c from Commune__c Where  CodeCanton4Chiffres__c='1201' OR CodeCanton4Chiffres__c='1202']);
       
        for (Integer i=0; i < createdCommunes.size(); i++) {
            System.debug('Value of canton after trigger fired: ' + createdCommunes[i].CantonId__c);
            // Test that the trigger correctly updated the RegionAdministrative
            System.assertEquals('OCCITANIE', createdCommunes[i].RegionAdministrative__c);
        }    
    }
}

Ty in advance for your help.