+ Start a Discussion
buggs sfdcbuggs sfdc 

Test class for Json Genrator

HI,

Please help me to write a test class for the below apex class method.

Thanks In Advance!
public void CallJsonmethod(){
        try{
            JSONGenerator gen = JSON.createGenerator(true);
            gen.writeStartObject();
            gen.writeStringField('Name', acc.Name);
            gen.writeBooleanField(’Stream__c', acc. Stream__c);
            gen.writeBooleanField(‘Q1', acc.Q1);
            gen.writeBooleanField(’Theatre__c', acc.Theatre__c);
            gen.writeBooleanField(‘MRR__C', acc.MRR__C);
            gen.writeBooleanField(‘CRR__c', acc.CRR__c);
            gen.writeBooleanField(‘Event__c', acc.Event__c);
            gen.writeEndObject();
            system.debug('***'+gen.getAsString());
            Http h = new Http();
            HttpRequest req = new HttpRequest();
            req.setEndpoint(endPoint);
            req.setMethod('POST');
            req.setHeader('x-api-key', xapiKey);
            req.setBody(gen.getAsString());
            HttpResponse res = new HttpResponse();
            res = h.send(req);
            system.debug(res.getBody());
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Account ' + acc.Name + ‘ changed please notify to your admin'));
        }catch(Exception ex){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage()));
        }

 
Best Answer chosen by buggs sfdc
Leo10Leo10
Hi 
You can write your test class like this 
@istest
private class MyaccountTest{

    @istest static void Testmethod1(){
    
    Account acc= new Account(Name='Test Account', Stream__c='someValue1',Q1='someValue2',Theatre__c='someValue3',MRR__C='someValue4',CRR__c='someValue5',Event__c='someValue6');
    insert acc;
    myaccount Myacc= new myaccount();
    string s= Myacc.CallJsonmethod();
    string expected='[ {  "Name" : "'+acc.Name+'",  "Stream__c" : "'+acc.Stream__c+'",  "Q1" : "'+acc.Q1+'",  "Theatre__c" : "'+acc.Theatre__c+'",  "MRR__C" : "'+acc.MRR__C+'",  "CRR__c" : "'+acc.CRR__c+'",  "Event__c" : "'+acc.Event__c+'"} ]';
    system.assertequals(expected,s.replaceAll('\n', '').replaceAll('\r',''));
    
    }

}

If you are getting any error please let me know
Thank you