Wednesday 11 March 2015

ENUM


An enum is an abstract data type with values that each take on exactly one of a finite set of identifiers that you specify. Enums are typically
used to define a set of possible values that don’t otherwise have a numerical order, such as the suit of a card, or a particular season of
the year. Although each value corresponds to a distinct integer value, the enum hides this implementation so that you don’t inadvertently
misuse the values, such as using them to perform arithmetic. After you create an enum, variables, method arguments, and return types
can be declared of that type.


public enum Season {WINTER, SPRING, SUMMER, FALL}
Season e = Season.WINTER;

public Season m(Integer x, Season e1) {
if (e1 == Season.SUMMER) {
return Season.SUMMER;
}
else{
return Season.WINTER;
}
}

System.debug(m(1,Season.SUMMER));

Tuesday 10 March 2015

Uniqueness of map keys of user-defined types is determined by the equals and hashCode methods,


public class PairNumbers {
    Integer x,y;

    public PairNumbers(Integer a, Integer b) {
        x=a;
        y=b;
    }

    public Boolean equals(Object obj) {
        if (obj instanceof PairNumbers) {
            PairNumbers p = (PairNumbers)obj;
            return ((x==p.x) && (y==p.y));
        }
        return false;
    }

    public Integer hashCode() {
        return (31 * x) * y;
    }
}

Use case:

Map<PairNumbers, String> m = new Map<PairNumbers, String>();
PairNumbers p1 = new PairNumbers(1,2);
PairNumbers p2 = new PairNumbers(3,4);
// Duplicate key
PairNumbers p3 = new PairNumbers(1,2);
PairNumbers p4 = new PairNumbers(2,1);

m.put(p1, 'first');
m.put(p2, 'second');
m.put(p3, 'third');
m.put(p4, 'third');


// Map size is 2 because the entry with 
// the duplicate key overwrote the first entry.
System.assertEquals(2, m.size());

// Use the == operator
if (p1 == p3) {
    System.debug('p1 and p3 are equal.');
}

// Perform some other operations
System.assertEquals(true, m.containsKey(p1));
System.assertEquals(true, m.containsKey(p2));
System.assertEquals(false, m.containsKey(new PairNumbers(5,6)));

for(PairNumbers pn : m.keySet()) {
    System.debug('Key: ' + pn);
}

List<String> mValues = m.values();
System.debug('m.values: ' + mValues);

// Create a set
Set<PairNumbers> s1 = new Set<PairNumbers>();
s1.add(p1);
s1.add(p2);
s1.add(p3);

// Verify that we have only two elements
// since the p3 is equal to p1.
System.assertEquals(2, s1.size());

Sunday 15 February 2015

Common Trigger Problems


  1. Cascading Triggres
  2. Apex governor Limits
  3. Null Refernce errors
  4. Too many Soql 

Redirecting to a Standard Object List Page

For buttons or links that navigate a user to a standard tab, you can redirect the content to present a list of standard objects.

Create a Visualforce page with the following markup:


<apex:page action="{!URLFOR($Action.Account.List, $ObjectType.Account)}"/>

Custom Labels and Error Messages

When set, the label attribute will be used for component-level error messages, for example, when a field is required or must be unique. Custom labels won't be used in custom error messages, and the default object field label will be used instead. If you set a label attribute to an empty string, the default object field label will be used in all error messages

Sunday 11 January 2015

Testing HTTP Callouts by Implementing the HttpCalloutMock Interface

global class MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('http://api.salesforce.com/foo/bar', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"foo":"bar"}');
        res.setStatusCode(200);
        return res;
    }
}
public class CalloutClass {
    public static HttpResponse getInfoFromExternalService() {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://api.salesforce.com/foo/bar');
        req.setMethod('GET');
        Http h = new Http();
        HttpResponse res = h.send(req);
        return res;
    }
}
@isTest
                        
private class CalloutClassTest {
     @isTest static void testCallout() {
        // Set mock callout class 
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        
        // Call method to test.
        // This causes a fake response to be sent
        // from the class that implements HttpCalloutMock. 
        HttpResponse res = CalloutClass.getInfoFromExternalService();
        
        // Verify response received contains fake values
        String contentType = res.getHeader('Content-Type');
        System.assert(contentType == 'application/json');
        String actualValue = res.getBody();
        String expectedValue = '{"foo":"bar"}';
        System.assertEquals(actualValue, expectedValue);
        System.assertEquals(200, res.getStatusCode());
    }
}

Saturday 10 January 2015

Testing SOSL


Use       Test.setFixedSearchResults


Class

public class MySearchClass{
    public Static void doSearch(String search){
        List<List<Sobject>> searchResult;
        searchResult=[FIND :search IN ALL FIELDS RETURNING Account];
        if(searchResult!=null){
            System.debug('in if'+searchResult);
            searchResult=[FIND :search IN ALL FIELDS RETURNING Account];
        }
        else{
            System.debug('in else'+searchResult);
            searchResult=[FIND :search IN ALL FIELDS RETURNING Account];
        }
    }
}

Test Class

@isTest
public class TestMySearchClass{
    private static testMethod void testMeth(){
        Account acc = new Account(Name='testBaljeet');
        insert acc;
        Test.setFixedSearchResults(new List<Id>{acc.id});
        MySearchClass.doSearch('test');
    }
}

Load TestData Using Static Resource CSV file in Test Class


@isTest
static testMethod void static_testResource(){
          List<sobject> cand=Test.loadData(Account.sObjectType,'testAccount');
}