Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I have an apex code as follows:

public with sharing class Account_Test {
    public String USerDate1 { get; set; }
    public List<Lead> ui{get;set;}
    public integer i;
    public List<Account> aa{get;set;}
    public Account_Test() {
     ui = new List<Lead>();
     ui = [SELECT Name,Id,OwnerID,FirstName, LastName, Company FROM Lead  WHERE User_Processed__c = False AND Download__c = True];
     aa = new List<Account>();
    }

    public PageReference chkinst() {
          Date myDate1;
          Integer i=0;
          if(String.IsBlank(UserDate1)){           
             ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Please enter Date'));
             return null;
           } else {
             myDate1 = date.valueOf(UserDate1);

           }

           Set<String> aSearchSet = new Set<String>();
            List<Lead> lList = ui;
            for (Lead l : lList) {
              aSearchSet.add(l.company);      
            }   
        Map<String,Account> companyToAccountMap = new Map<String,Account> ();
        for (Account a: [select id, Name from Account where name IN :aSearchSet])
        companyToAccountMap.put(a.name,a);

           for (Lead l : lList) {
             if (!companyToAccountMap.containsKey(l.company)){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, l.company + ' does not exist for ' + l.FirstName + ' ' + l.LastName));
                i = i +1;
             }    
           }

           if(i == 0) {
             ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'All Leads have Correct Institution names '));
           }
            return null;
    }

}

And the following test code:

@isTest(seealldata=false) 
private class Account_TestClass {

    static testMethod void validateAccount_Test() {      
        List<Account> accounts = new List<Account>{};
        String insName = 'Company Name';
        Account a = new Account(Name =insName , Country__c='United States');
        accounts.add(a);
        insert accounts;
        Account getAccountID = [SELECT ID FROM Account Where Name = :insName ];
        Account_Test myNotes2 = new Account_Test(); 
        myNotes2.aa= accounts;
       Account_Test myNotes = new Account_Test(); 
       myNotes.USerDate1 =  '2014-01-02';  
           myNotes.chkinst();

    }
}

The test code only achieves 75% coverage,

I’m having trouble using assert command,

Actually I don’t fully understand how to use assert in this case,

For example

ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Please enter Date'));
return null;

Is not covered,

Can someone tell me, how I can change/add to the code?

So I can cover the two lines above,

share|improve this question
add comment

1 Answer

up vote 8 down vote accepted

Create a second test method that sets up the test data so that the conditional if(String.IsBlank(UserDate1)) evaluates to true.

@isTest(seealldata=false) 
private class Account_TestClass {

    static testMethod void validateAccountUserDate1Blank_Test() {      
        List<Account> accounts = new List<Account>{};
        String insName = 'Company Name';
        Account a = new Account(Name =insName , Country__c='United States');
        accounts.add(a);
        insert accounts;
        Account getAccountID = [SELECT ID FROM Account Where Name = :insName ];
        Account_Test myNotes2 = new Account_Test(); 
        myNotes2.aa= accounts;
       Account_Test myNotes = new Account_Test(); 
       // Set to empty string or just don't set it so it's null
       myNotes.USerDate1 =  '';  

       Test.startTest();
       PageReference retPageRef = myNotes.chkinst();
       Test.stopTest();

       // Assert statements (see below notes)

    }
}

Then you can assert the following:

  1. That the PageReference returned is null. In your test code assign the result of the method call to a PageReference, e.g., PageReference retPageRef = myNotes.chkinst();
  2. That the ApexPages.hasMessages(ApexPages.Severity.INFO).
  3. Optionally, the text of the message

Corresponding Code

System.assertEquals(null, retPageRef, 'PageReference returned should be null');
System.assertEquals(true, ApexPages.hasMessages(ApexPages.Severity.INFO), 'Should have at some INFO messages');
System.assertEquals('Please enter Date', ApexPages.getMessages().get(0).getSummary(), 'Wrong info message');
share|improve this answer
6  
Note that 100% coverage is practically impossible for all but the most trivial of classes. A more reasonable goal is 90%. What's more important is that the tests actually verify business logic using asserts. –  sfdcfox Jan 2 at 22:14
    
Agree. If you create solid unit test suites that test your code well, the 90%+ is a natural byproduct. Still, the code coverage analysis provided by SFDC can definitely help to make sure I've caught everything I can. –  Peter Knolle Jan 2 at 22:24
    
I disagree with @sfdcfox here, while 90% is a reasonable goal, 100% is definitely possible in all but a small number of cases, namely those that make callouts. There may be some cases where exceptions or branched logic are hard to recreate via test classes, but that could also indicate the "tested" code needs refactoring. Granted, there's usually not much different between 90 and 100%, it's just nice to see the three digits instead of two. –  James Loghry Jan 2 at 23:19
3  
@JamesLoghry While I agree it's nice, practically speaking, the only guaranteed 100% coverage classes are those with no DML operations or callouts, because if you're not checking for DML errors, even when none are "possible", then you're not doing your job as a developer. Post install validation rules could cause a failure, for example, when none is theoretically possible. Without adding a specific test-only fail mechanism (which simply bloats code), 100% isn't realistic. 95-98% usually is, though. 100% is not achievable in the majority of cases simply because not all errors are testable. –  sfdcfox Jan 3 at 6:08
    
For the specific controller posted in the question, the relevant things to test are whether a) the proper messages are being emitted and b) the correct result PageReference is as expected. Peter's asserts do just that. In practice, I tend to follow @sfdcfox and don't test every catch block in my code if it requires setting up an artificial NPE or list exception to get the catch block to execute. However, I test catch blocks if rollbacks are coded, special purpose emails/logs are constructed, or I just want to make sure that my error handling infrastructure works as expected –  crop1645 Jan 3 at 18:05
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.