2013-01-07 3 views
2

텍스트 필드가있는 VF 페이지 양식이 있습니다. 이 텍스트 필드의 값은 기존의 기회 사용자 정의 필드와 비교됩니다. 이 텍스트 필드의 값이 기회에 존재하면 나는 새 레코드를 만듭니다.Salesforce.com Apex 테스트 클래스 문제 : 하드 코드 기회 기회 사용자 정의 필드 값

Apex 테스트 클래스를 만들 때를 제외하고 모든 것이 잘 작동합니다.

나는 기회를 만들고 사용자 정의 필드의 값을 하드 코딩해야합니다. 불행히도이 필드는 쓰기 가능하지 않습니다.

이전에이 문제가 발생 했습니까? 오류 :

내가지고있어 오류가 컴파일 오류 :이 필드를 잘 쓰기되지 않습니다 : 라인 9 열 (103)

에서 Opportunity.Deal_Registration_ID__c 아래는 내 에이펙스 클래스입니다.

내 테스트 클래스가 맨 아래에 있습니다.

도움을 주시면 대단히 감사하겠습니다.

건배! 롬멜

public with sharing class VaultVF { 

public Vault__c vault {get; set;} 
public List<String> errorMsgs {get; set;} 
public String saveResult {get; set;} 
public String dealReg {get; set;} 
public String oppId {get; set;} 
public String email {get; set;} 
public Boolean scenario1{get; set;} 
public Boolean scenario2{get; set;} 
public Boolean scenario3{get; set;} 

// Generates country dropdown from country settings 

public List<SelectOption> getCountriesSelectList() { 
    List<SelectOption> options = new List<SelectOption>(); 
    options.add(new SelectOption('', '-- Select One --'));   

    // Find all the countries in the custom setting 

    Map<String, Country__c> countries = Country__c.getAll(); 

    // Sort them by name 

    List<String> countryNames = new List<String>(); 
    countryNames.addAll(countries.keySet()); 
    countryNames.sort(); 

    // Create the Select Options. 

    for (String countryName : countryNames) { 
     Country__c country = countries.get(countryName); 
     options.add(new SelectOption(country.Two_Letter_Code__c, country.Name)); 
    } 
    return options; 
} 

//Constructor, set defaults 
public VaultVF(ApexPages.StandardController controller) { 

    vault = (vault__c)controller.getRecord(); 

    //Populate list of random characters for CAPTCHA verification 
    characters = new List<String>{'a','b','c','d','e','f','g','h', 
     'i','j','k','m','n','p','q','r','s','t','u','v','w', 
     'x','y','z','1','2','3','4','5','6','7','8','9' 
    }; 

    errorMsgs = new List<String>(); 

} 

//Determine if page has error so errors message can be displayed 
public boolean getHasErrors(){ 
    if(ApexPages.hasMessages() == true){ 
     if(errorMsgs == null){ 
      errorMsgs = new List<String>();    
     } 

     //Loop through errors and add to a list 
     for(ApexPages.Message m : ApexPages.getMessages()){ 
      if(m.getSummary().startsWith('Uh oh.')){ 
       errorMsgs.add(String.valueOf(m.getSummary())); 
      } 
     } 
    } 
    return ApexPages.hasMessages();  
} 

public void save(){ 
    errorMsgs = new List<String>(); 

    //Make sure captcha was correct 
    if(validateCAPTCHA() == false){ 
     errorMsgs.add('Verification code was incorrect.'); 
     captchaInput = ''; 
    } 

    //Make sure the Scenario is selected   
    if(scenario1 == true){ 
     vault.Scenario__c = 'BIG-IP as a Firewall'; 
    }else if(scenario2 == true){ 
     vault.Scenario__c = 'BIG-IP providing firewall service in conjunction with other vendors'; 
    }else if(scenario3 == true){ 
     vault.Scenario__c = 'BIG-IP front ending Firewalls'; 
     if(vault.Load_Balancer_is_a_Firewall__c == null){ 
      errorMsgs.add('Please specify if the load balancer is a firewall.'); 
     } 
     if(vault.Providing_DDos_Connection__c == null){ 
      errorMsgs.add('Please specify if this is providing DDos connection level protection for firewalls or both.'); 
     } 
     if(vault.Providing_DDos_protection_except_ASM__c == null){ 
      errorMsgs.add('Please specify if we are providing DDos protection (except ASM).'); 
     } 
     if(vault.No_Traffic_Traverse__c == null){ 
      errorMsgs.add('Please specify if there is Traffic that does not traverse the Firewalls.'); 
     } 
     if(vault.Firewall_Vendor_Name__c == null){ 
      errorMsgs.add('Please specify a Firewall Vendor.'); 
     } 
    } else { 
     errorMsgs.add('Please select one of three Scenarios that is similar to your setup'); 
    }  

    //-----Need to make sure deal registration number on opportuntiy is valid.----- 

    //Set some sort of is valid deal reg flag to false. We will assume the deal reg Id entered is invalid until we determine it is valid 
    vault.isValidDealReg__c = false; 

    //Query Account Id, and Deal_Registration_Id__c from the opportunity object where the deal registration Id equals the value entered in the form 
    List<Opportunity> opps = [select Id, Deal_Registration_ID__c from Opportunity where Deal_Registration_ID__c = :vault.Deal_Registration__c]; 

    //check to see if registration id on the opp match the entered value  
    if(opps.size() > 0 && opps[0].Deal_Registration_ID__c == vault.Deal_Registration__c){ 

    //If they do match set the valid deal reg Id flat to true 
     vault.isValidDealReg__c = true; 
     vault.Related_Opp__c = opps[0].Id; 

    //If they don't match then query all contacts on the account related to the opportunity 
    } 

    //If is valid deal reg flag is false add a message to the errorMSgs list indicated the entered 
    //deal registration is not valid with details on who they should contact 
    if(errorMsgs.size()>0){ 
     //stop here 
    } else if(vault.isValidDealReg__c == false){ 
     errorMsgs.add('Deal Registration # was incorrect. Please contact your representative.'); 
    } else { 
     try{ 
      vault.Status__c = 'Application Received'; 
      insert vault; 
      saveResult = 'success'; 

     }catch(exception e){ 
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, 'Uh oh. Something didn\'t work quite right. Please contact [email protected] for assistance. \n\n' + e.getMessage()));     
      saveResult = 'fail'; 
     } 
    } 

} 

//------------------------Code for CAPTCHA verification---------------------------- 
public String captchaInput {get; set;} 
List<String> characters; 
String char1; 
String char3; 
String char5; 

//This methods simply returns a random number between 0 and the size of the character list 
public Integer randomNumber(){ 
    Integer random = Math.Round(Math.Random() * characters.Size()); 
    if(random == characters.size()){ 
     random--; 
    } 
    return random; 
} 

/*Here we have 6 get methods that return 6 random characters to the page. 
For chars 1,3, and 5 (the black characters) we are saving the the values so 
that we can compare them with the user's input */ 
public String getChar1(){ 
    char1 = characters[randomNumber()]; 
    return char1; 
} 
public String getChar2(){ 
    return characters[randomNumber()]; 
} 
public String getChar3(){ 
    char3 = characters[randomNumber()]; 
    return char3; 
} 
public String getChar4(){ 
    return characters[randomNumber()]; 
} 
public String getChar5(){ 
    char5 = characters[randomNumber()]; 
    return char5; 
} 
public String getChar6(){ 
    return characters[randomNumber()]; 
} 

public String correctAnswer(){ 
    return char1 + char3 + char5; 
} 

public Boolean validateCAPTCHA(){ 
    if(captchaInput.length() == 3 && captchaInput.subString(0,1) == char1 && captchaInput.subString(1,2) == char3 && captchaInput.subString(2,3) == char5){ 
     return true; 
    }else{ 
     return false; 
    } 
} 

}

다음

테스트 클래스

@isTest 
public class VaultVFTEST { 

/*This tests the VaultVF class on the Vault__c object*/ 

static testMethod void VaultVFTEST() { 

    //Create opp, hardcode the Deal_Registration_Id__c field with 'x111111111' and insert opp 
    Opportunity opp = new Opportunity(Name='test opp', StageName='stage', Deal_Registration_Id__c='x111111111', Probability = 95, CloseDate=system.today()); 
    insert opp; 

    //Create and insert Vault record 
    Vault__c vault = new Vault__c(
     Deal_Registration__c = 'x111111111', 
     Scenario__c = 'BIG-IP front ending Firewalls', 
     isValidDealReg__c = true, 
     Status__c = 'Application Received', 
     Load_Balancer_is_a_Firewall__c = 'Yes', 
     Providing_DDos_Connection__c = 'Firewalls', 
     Providing_DDos_protection_except_ASM__c = 'Yes', 
     No_Traffic_Traverse__c = 'Yes', 
     Firewall_Vendor_Name__c = 'Firewall Vendor Company', 
     First_Name__c = 'Test First Name', 
     Last_Name__c = 'Test Last Name', 
     Company_Name__c = 'Test Company Name', 
     Phone__c = '(206) 946-3126', 
     Email__c = '[email protected]', 
     Country__c = 'United States', 
     Additional_Info__c = 'Test Additional Info', 
     Related_Opp__c = opp.Id 
    ); 

    //Now insert the vault record to invoke the VaultVF class 
    Test.startTest(); 
    insert vault; 
    Test.stopTest(); 

    //Assertion Testing - Check to make sure the Deal_Registration__c value 
    //matches the Deal_Registration_Id__c value of the related opportunity 
    for(Vault__c v : [select Id, Deal_Registration__c from Vault__c where Deal_Registration__c IN :vault]){ 
     system.assertEquals(v.Deal_Registration__c, opp.Deal_Registration_Id__c); 
    } 
} 
} 
+0

당신은 나의 일 "어 오"에 대한이를;)하지만 당신은 또한 컴파일 오류의 테스트 클래스 및 일식 오류를 (내가 이해 게시 할 수 있으며, 그것은 특정 분야에 대해 불평)? 수식, 자동 숫자 등은 실제로 쓰기가 불가능합니다. 먼저 레코드를 삽입하고 어떻게 든 VF 페이지로 전달해야합니까? 또는 CAPTCHA에 관한 것이면 - Test.isRunningTest()를보고 가짜 값이 아닌 임의 값을 하드 코딩하는 데 사용하십시오. – eyescream

답변

1

Opportunity.Deal_Registration_ID__c 필드 유형 무엇입니까? 수식 필드 또는 자판 번호 인 경우 실제로는 Apex에서 쓸 수 없습니다.

일반적으로 이러한 시나리오에서는 Opportunity (이 필드 세트없이)를 삽입 한 다음 성공적인 삽입 후에 데이터베이스에서 다시 읽어야합니다. 자판 번호 인 경우 자체적으로 마술이 발생합니다 (수식 번호 인 경우 & 번 연속으로 허위 번호를 부여하는 것이 가장 좋은 생각이라고 말하지는 않겠지 만), 수식 필드 인 경우 - 모두를 설정했는지 확인하십시오. 삽입 전에 계산에 사용되는 필드.

그래서 이런 일이 트릭을 수행해야합니다

Opportunity opp = new Opportunity(Name='test opp', StageName='stage', Probability = 95, CloseDate=system.today()); 
insert opp; 
opp = [SELECT Id, Name, Deal_Registration_ID__c FROM Opportunity WHERE Id = :opp.Id]; 

// Optionally - make sure value was set 
System.assertNotEquals(null, opp.Deal_Registration_ID__c); 
System.assert(opp.Deal_Registration_ID__c.length() > 0); // if it's a String 

Vault__c vault = new Vault__c(
    Deal_Registration__c = opp.Deal_Registration_ID__c , 
    Scenario__c = 'BIG-IP front ending Firewalls', 
    isValidDealReg__c = true, 
    Status__c = 'Application Received', 
    Load_Balancer_is_a_Firewall__c = 'Yes', 
    Providing_DDos_Connection__c = 'Firewalls', 
    Providing_DDos_protection_except_ASM__c = 'Yes', 
    No_Traffic_Traverse__c = 'Yes', 
    Firewall_Vendor_Name__c = 'Firewall Vendor Company', 
    First_Name__c = 'Test First Name', 
    Last_Name__c = 'Test Last Name', 
    Company_Name__c = 'Test Company Name', 
    Phone__c = '(206) 946-3126', 
    Email__c = '[email protected]', 
    Country__c = 'United States', 
    Additional_Info__c = 'Test Additional Info', 
    Related_Opp__c = opp.Id 
); 
+0

감사합니다. 나는 우리가 가까워지고 있다고 생각한다. 불행히도 다음 오류가 발생합니다. 메시지 : System.DmlException : 삽입하지가 못했습니다. 행 0에 대한 첫 번째 예외. 제 오류 : STRING_TOO_LONG, Deal_Registration : 데이터 값이 너무 큰 : 안 공식 등록 (최대 길이 = 20) : Deal_Registration__c] 스택 추적 : Class.VaultVFTEST.VaultVFTEST : 라인 41 는 시간이 1 열의주세요 도움. 감사합니다, 롬멜 –

+0

글쎄, 그건 당신의 자신의 사용자 정의 필드입니다 : D 누가 그것을 만든 사람 (설정 -> 만들기 -> 개체 -> 거래 등록 -> 필드 및 더 오래 만들기 위해이 필드를 편집 할 수 있는지 여부를 결정 최대 255자를 추측 할 것입니다.) 테스트에서'opp.Deal_Registration_ID_c.left (20)'를 호출해야합니다. 이상적으로 두 필드의 크기가 같아야합니다. Setup -> Create -> Opportunities -> Fields를 선택하십시오. (그러한 숫자를 잘라내는 것이 유효한 생각처럼 들리지는 않는다;)) – eyescream