2016-08-30 6 views
0

I'v가 sandbox의 salesforce 클래스를 만들었지 만 제대로 작동하지만, 프로덕션 환경에 배포 할 때 낮은 코드가 발생합니다. covarage. 내가 아는 모든 것을 시도했지만 고양이가 해결책을 찾았습니다. 코드가 도움이 되었습니까?Saleseforce 코드 공모전이 낮고 (53 %) 이유는 모르겠다.

public Class CandidateFileUploads_Ver1{ 

public String parentId ; 
public String idxVal {get;set;} 
public Map<String, Attachment> attachments {get;set;} 
public Map<String, Attachment> attachmentsDup {get;set;} 

public Boolean validateUser {get;set;} 
public String multipulDocs {get;set;} 
public String userMessage {get;set;} 

private static final Map<String, String> descriptionNameMap = new Map<String, String>{ 
'Upload a scan of the Passport'=>'Passport', 
'Upload a Resume (CV)'=>'Resume (CV)'}; 

private static final Map<String, String> descriptionCheckFieldMap = new Map<String, String>{ 
'Upload a scan of the Passport'=>'Passport_Attached__c', 
'Upload a Resume (CV)'=>'CV_Attached__c'}; 


public CandidateFileUploads_Ver1(ApexPages.StandardController controller){ 

    idxVal = ''; 
    validateUser = true; 
    multipulDocs = System.Label.multiple_docs; 
    userMessage = ''; 

    checkUserValid(); 
    attachments = new Map<String, Attachment>();  
    attachmentsDup = new Map<String, Attachment>(); 

    parentId = System.currentPageReference().getParameters().get('Id'); 
    //parentId = '0034E00000FVJzA'; 
    List<Attachment> existingAttachments = fetchAllAttachments(parentId);//get all attachements for thew user 

    for(String key :descriptionNameMap.keySet()){ 
     String kokp = descriptionCheckFieldMap.get(key); 
     attachments.put(key.toLowerCase(), new Attachment(parentId=parentId, Description=key, body=null,Name = kokp)) ; 
    }  

    for(Attachment attach :existingAttachments){ 
     attach.body = null; 
     attachments.put(attach.Description.toLowerCase(), attach);    
    } 
} 

public void checkUserValid(){ 
    String hours = System.Label.hours; 
    String whitelist = System.Label.whitelist; 
    ID pId = System.currentPageReference().getParameters().get('Id'); 
    Boolean validateUser = true; 
    String userMessage; 

    Contact parenter = new Contact(Id=pId); 
    // Validate Proccess status: get proccess string status 
      String getStatus = parenter.Process_Status__c; 
      String[] whitelistArr = whitelist.split(',');// split proccess string 

      Boolean checkWhiteList = false; 
      for(String val : whitelistArr){ 
       if(val == getStatus) { 
        checkWhiteList = true; 
       } 
      } 

      if(validateUser != checkWhiteList){ 
       validateUser = false; 
       userMessage = System.Label.error_not_premitted; 
       return; 
      } 

    //Validate Dates 
      //Datetime getLinktimestamp = (Datetime) contactSObject.get('linktimestamp__c'); 
      Datetime getLinktimestamp = parenter.linktimestamp__c; 
      Datetime getValidTime = getLinktimestamp.addHours(Integer.valueof(hours.trim())); //add 48 hours 
      Datetime timeNow = System.now(); 

      if(getValidTime < timeNow){//if if more then 48 hours 
       validateUser = false; 
       userMessage = System.Label.error_expired; 
       return; 
      } 
} 


public Datetime getLinktimestamp(){ 
    ID pId = System.currentPageReference().getParameters().get('Id'); 
    Datetime accts = [SELECT linktimestamp__c FROM Contact WHERE Id=:pId].linktimestamp__c; 
    return accts; 
} 


public List<Contact> contactObj(){ 
    ID pId = System.currentPageReference().getParameters().get('Id'); 

    sObject mySObject =[SELECT linktimestamp__c,Process_Status__c FROM Contact WHERE Id=:pId]; 
    //Datetime llli = s.linktimestamp__c; 
    String strObjectName = String.valueOf(mySObject.get('linktimestamp__c')); 

    List<Contact> obj = [SELECT linktimestamp__c,Process_Status__c FROM Contact WHERE Id=:pId]; 
    return obj; 
} 

public void uploadAttachment(){  
    List<Attachment> uploads = new List<Attachment>() ; 
    List<Attachment> deletes = new List<Attachment>() ; 

    try{ 
     for(integer i = 0 ; i < attachments.values().size() ; i++){ 

      Attachment attach = attachments.values()[i] ; 
      if(attach.parentId == NULL){ 
         attach.parentId = System.currentPageReference().getParameters().get('Id'); 
      } 
      //this is a file that was uploaded now 
      if(attach.body != NULL){ 
       //remove current attachement before uploading a new one 
       if(attach.Id != NULL){ 
        deletes.add(attachments.values().remove(i)); 
       } 

       attach.Name = renameFile(attach.Name, attach.Description); 
       uploads.add(attach) ; 
      } 
     } 

     if(!deletes.isEmpty()){ 
      delete deletes ; 
     } 

     if(!uploads.isEmpty()){   
      for(Attachment atchmnt :uploads){ 
       atchmnt.Id = null; 
      } 

      insert uploads; 

      Contact parent = new Contact(Id=parentId); 

      for(Attachment attach :getUpdatedAttachments(uploads).values()){ 
       attach.body = null; 
       attachments.put(attach.Description.toLowerCase(), attach); 

       parent.put(descriptionCheckFieldMap.get(attach.Description), true);      
      } 

      update parent; 

      ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.info,'Attachment upload Successfully'); 
      ApexPages.addMessage(myMsg); 
     } 

    }   
    catch(exception e){ 
     ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'An Error occured when uploading attachment'); 
     ApexPages.addMessage(myMsg); 
    } 
} 

public void removeRow(){ 
    Attachment a = attachments.get(idxVal.toLowerCase()); 

    Contact parent = new Contact(Id=parentId); 
    parent.put(descriptionCheckFieldMap.get(a.Description), false); 

    delete a; 
    update parent; 

    system.debug('attachments before: ' + attachments); 
    attachments.put(a.Description.toLowerCase(), new Attachment(parentId = parentId, description = a.description, body=null)); 
    system.debug('attachments after: ' + attachments); 
}  

private static String renameFile(String fileName, String description){ 
    String newName = descriptionNameMap.get(description); 
    if(String.isNotBlank(fileName) && fileName.contains('.')){ 
     newName += fileName.substring(fileName.lastIndexOf('.'), fileName.length()); 
    } 

    return newName; 
} 

private static Map<String,Attachment> getUpdatedAttachments(List<Attachment> attachList){ 

    Map<String,Attachment> attMap = new Map<String,Attachment>(); 

    for(Attachment att : [SELECT Id,Name,Description 
             FROM Attachment 
             WHERE Id = :attachList]){ 
     attMap.put(att.Description.toLowerCase(), att) ;  
    } 

    return attMap; 
} 

public List<Attachment> fetchAllAttachments(String parentId){ 

    return [SELECT Id,Name,Description,parentId 
      FROM Attachment 
      WHERE ParentId =: parentId 
      AND Description IN :descriptionNameMap.keySet()]; 
} 

}

+0

모든 답변을 주셔서 감사합니다. 하지만 주요 문제는 테스트 클래스를 작성해야한다는 것이 었습니다 (미안하지만 그 사실을 알지 못했습니다). 그리고 그것은 잘 작동합니다. – Eli

답변

1

개발자 콘솔을 사용하여 코드의 일부분을 덮어 쓰지 않았는지 확인한 다음 테스트를 조정할 수 있습니다. 개발자 콘솔에서 코드를 편집 할 때 페이지 왼쪽 상단에 '코드 적용 범위'옵션이 있습니다.

1

당신은 무엇을 의미합니까 "나는 내가 알고 있지만 고양이가 해결책을 찾을 모든 노력을"? Salesforce 요구 사항 - Apex 코드는 적어도 75 % 이상의 테스트가 적용되어야합니다. 평균 커버리지가 75 % 임계 값을 충족시키지 않으면 배포가 실패합니다.

유일한 해결책은 코드에 대한 테스트를 작성하는 것입니다.

+0

어떻게 생성자에 대한 테스트를 작성할 수 있으며 인수로 메소드를 작성할 수 있습니까? – Eli

+1

테스트 메소드에서 생성자 또는 메소드를 인수로 호출하지 못하게하는 이유는 무엇입니까? 예를 들어, 다음은 컨트롤러 생성자 테스트에 대한 설명입니다 - https://developer.salesforce.com/forums/?id=906F00000008zbRIAQ –

+2

또한 https://developer.salesforce.com/docs/atlas.en-us.pages. meta/pages/pages_controller_error_handling.htm이 도움이 될 수 있습니다. –