I am deserializing a response with a class. In my test class i am passing dummy JSON String, but its covering all the lines in class.  public class CustomerAccount  {      public class OrgDetails{         @AuraEnabled         public String orgId {get;set;}         @AuraEnabled         public String org_name {get;set;}     }      @AuraEnabled     public String account_no {get;set;}     @AuraEnabled      public List&lt;OrgDetails&gt; orgDetail {get;set;}      public static CustomerAccount  parse(String json) {         return (CustomerAccount ) System.JSON.deserialize(json, CustomerAccount .class);     }   }  When I am calling parse with dummy JSON then its only covering parse method and one other property.  Calling only parse() method is not enough for covering this class(CustomerAccount)?
3698
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, including more unit test resources, navigate to the  tag.  This canonical question is intended to address several classes of common questions by providing a quick summary and links to comprehensive resources:   How is code coverage obtained and calculated? How do I increase my coverage?  Why can't I cover these lines? Why isn't the body of my loop or conditional statement covered?
80355
I have this struct:  struct Map {     public int Size;      public Map ( int size )     {         this.Size = size;     }      public override string ToString ( )     {         return String.Format ( "Size: {0}", this.Size );     } }   When using array, it works:  Map [ ] arr = new Map [ 4 ] {     new Map(10),     new Map(20),     new Map(30),     new Map(40)};  arr [ 2 ].Size = 0;   But when using List, it doesn't compile:  List&lt;Map&gt; list = new List&lt;Map&gt; ( ) {     new Map(10),     new Map(20),     new Map(30),     new Map(40)};  list [ 2 ].Size = 0;   Why?
23661
Context Around this Code: I am making a schedulable class run each Sunday to track a couple of metrics important to the team.   Question: I am looking to consolidate DML operations and a big part of this is understanding pass by reference vs pass by value.  I want to pass the salesOps user object to the method SDREfficiencyLastWeek. I made the return type void, because I figured that I will be passing this by reference and I can make all the updates in the method without having to anything.   Why I am confused:    I read the above article and am thrown off by the following statement:  "Non-primitive data type arguments, such as sObjects, are also passed into methods by value. "   If the object is indeed passed by reference, then the query for the salesOps user in my code should be sufficient enough to edit all fields on that object without actually having to state each field in the query.  global class SDREfficientMetricsSchedulable implements Schedulable  {     global void execute(SchedulableContext sc)      {         User salesOps = [SELECT ID FROM USER WHERE id = '0056A000002Z3p9QAC'];         List&lt;String&gt; queries = new List&lt;String&gt;();          String contactsWorked_lastWeek  = 'select count(id) results from contact where LastActivityDate = last_week';         queries.add(contactsWorked_lastWeek);          String demosSet_lastWeek            = 'select count(id) results from form__c where CreatedDate = last_week';         queries.add(demosSet_lastWeek);          String demosCompleted_lastWeek  = 'select count(id) results from opportunity where (stagename = \'Unqualified Demo Completed\'  OR stagename = \'Qualified Demo Completed\' )  and RecordTypeId = \'0126A000000yudDQAQ\' and CloseDate = last_week';         queries.add(demosCompleted_lastWeek);          String qualifiedDemos_lastWeek  = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and isclosed = false and  SDR_Owner__c != null and CreatedDate = last_week';         queries.add(qualifiedDemos_lastWeek);          String closedWon_lastWeek       = 'select count(id) results  from opportunity where RecordTypeId = \'0126A0000004Ao6QAE\' and iswon = true and  SDR_Owner__c != null and CloseDate = last_week';         queries.add(qualifiedDemos_lastWeek);            SDREfficiencyLastWeek(queries, salesOps);          update salesOps;     }       public void SDREfficiencyLastWeek(List&lt;String&gt; queries, User salesOps )     {        }  }
114132
I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).
86715
I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is  if you want to look at all of the code.  Here are the important parts:  private RpcMap map;  public &lt;X&gt; X get(String property) {   if (allowNestedValues &amp;&amp; NestedModelUtil.isNestedProperty(property)) {     return (X)NestedModelUtil.getNestedValue(this, property);   }   return map == null ? null : (X) map.get(property); }   X is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the &lt;X&gt; in the public method signature.  I've tried to call this method with the following two examples to see what happens:  public Date getExpiredate() {     return  get("expiredate"); }  public String getSubject() {     return  get("subject"); }   They compile and show no errors or warnings.  I would think at the very least I would have to do a cast to get this to work.  Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime?  This seems counter to what generics are supposed to do.  Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better?  I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.
118759
Question  I'm writing some code that needs to be able to get the values of the parameters from the method that called into the class. I know how to get all the way to the ParameterInfo[] array, but I don't know how to then get the values. Is this even possible?  If it is, I think it has something to do with using the MethodBody property from the MethodInfo object, which allows you to inspect the IL stream, including properties, but I don't know how to do it, and I haven't found applicable code on Google.  Code  // Finds calling method from class that called into this one public class SomeClass {     public static void FindMethod()     {         for (int i = 1; i &lt; frameCount; i++)         {             var frame = new StackFrame(i);             var methodInfo = frame.GetMethod();             if (methodInfo.DeclaringType != this.GetType())             {                 string methodName = frame.GetMethod().Name;                 var paramInfos = methodInfo.GetParameters();                  // Now what?? How do I get the values from the paramInfos                  break;             }             else if (i == frameCount - 1)             {                 throw new TransportException("Couldn't find method name");             }         }     } }
106280
Object o = new Long[0] System.out.println( o.getClass().isArray() ) System.out.println( o.getClass().getName() ) Class ofArray = ???   Running the first 3 lines emits;  true [Ljava.lang.Long;   How do I get ??? to be type long?   I could parse the string and do a Class.forname(), but thats grotty.   What's the easy way?
107559
I am adding cookie to my page in the controller using  ApexPages.currentPage().setCookies(new Cookie[]{CookieName});  When am trying to get the code coverage, my test class is not covering the above line.  How to get the code coverage for the above setcookie method in the test class.
60121
This is what my JSON looks like: {"series":[{,"points":[{"ts":"1473850836254","value":"11.27"},{"ts":"1473851256637","value":"6.44"}]}]}  I am trying to access the values in "points" by calling something like: data.series.points[0].ts       Void Start(){     IncomingData data = IncomingData.CreateFromJSON(jsonResponse.text);     print("Series point length" + data.series.points.Count);     print("Series point 0" + data.series.points.get_Item[0].ts); // error     }   //----------------------------------------- classes -------------------------      [System.Serializable]     public class IncomingData     {         public Series series;         public static IncomingData CreateFromJSON(string json)         {                return JsonUtility.FromJson&lt;IncomingData&gt;(json);          }     }      [System.Serializable]     public class Series     {         public List&lt;Points&gt; points = new List&lt;Points&gt; { };     }       [System.Serializable]     public class Points     {         public int ts;         public int value;     }   My error:  // error CS0021: Cannot apply indexing with [] to an expression of type `method group'
112656
I have a problem with FeedItems in my Test class, it's very weird behaviour Does someone explain to me why this happens?  Callout Class  public with sharing class Callout {  public static void runProccess(Case[] records) {     Database.executeBatch(new CalloutBatch(records), 10); }  public static void send(Case[] records) {     Case[] toUpdate = new Case[]{};       for (case record : records) {         HttpRequest req = new HttpRequest();         req.setEndpoint('callout:test/SOME_URL');         req.setMethod('POST');         req.setHeader('Content-Type', 'application/json');         req.setBody('');         Http http = new Http();         HTTPResponse res = http.send(req);          Map&lt;String, Object&gt; response = (Map&lt;String, Object&gt;) JSON.deserializeUntyped(res.getBody());          toUpdate.add(new Case(Id = (Id) response.get('Id'), Status = (String) response.get('Status')));     }      update toUpdate;  } }   CalloutBatch Class  global with sharing class CalloutBatch implements Database.Batchable&lt;Case&gt;, Database.AllowsCallouts{  private final Case[] records;  global CalloutBatch (Case[] records) {     this.records = records; }  global Iterable&lt;Case&gt; start(Database.BatchableContext BC) {     return records; }  global void execute(Database.BatchableContext BC, Case[] scope) {     Callout.send(scope); }  global void finish(Database.BatchableContext BC) { } }   Test Class  @IsTest  private class CalloutTest { @IsTest static void shouldReaciveData() {     String status = 'Closed';     Case caseRecord = new Case(Type = 'Web', Status = 'New');     insert caseRecord;      //insert new FeedItem(ParentId = caseRecord.Id, Visibility='AllUsers', Type = 'TextPost', Body = '');      System.assertEquals(0, [SELECT Count() FROM Case WHERE Id = :caseRecord.Id AND Status = :status]);      Test.startTest();     Test.setMock(HttpCalloutMock.class, new CalloutTestMock(caseRecord.Id, status));     Callout.runProccess(new Case[]{caseRecord});     Test.stopTest();      System.assertEquals(1, [SELECT Count() FROM Case WHERE Id = :caseRecord.Id AND Status = :status]); } }   Mock Class  public with sharing class CalloutTestMock implements HttpCalloutMock {  private Id recordId; private String status;  public CalloutTestMock(Id recordId, String status) {     this.recordId = recordId;     this.status = status; }  public HTTPResponse respond(HTTPRequest req) {     HttpResponse response = new HttpResponse();      response.setStatusCode(200);     response.setBody('{"Id": "' + recordId + '", "Status": "' + status + '"}');      return response; } }   This code works, but when I uncomment insert FeedItem in Test Class I receive an error message:     System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out   Class.Callout.send: line 23, column 1   Class.CalloutBatch.execute: line 20, column 1   FeedItem doesn't have an impact on this functionality, (I don't have any Process Builders, triggers etc. on FeedItem object)
37382
I'm a C++ guy learning Java. I'm reading Effective Java and something confused me. It says never to write code like this:  String s = new String("silly");   Because it creates unnecessary String objects. But instead it should be written like this:  String s = "No longer silly";   Ok fine so far...However, given this class:  public final class CaseInsensitiveString {     private String s;     public CaseInsensitiveString(String s) {         if (s == null) {             throw new NullPointerException();         }         this.s = s;     }     :     : }  CaseInsensitiveString cis = new CaseInsensitiveString("Polish"); String s = "polish";    Why is the first statement ok? Shouldn't it be   CaseInsensitiveString cis = "Polish"; How do I make CaseInsensitiveString behave like String so the above statement is OK (with and without extending String)? What is it about String that makes it OK to just be able to pass it a literal like that? From my understanding there is no "copy constructor" concept in Java?
54783
Is there any way to deserialize JSON into an object using JSON.deserialize if some of the property names in the JSON are reserved words in apex? I want to do something like this:  string jsonString = '{"currency" : "ABC"}'; public class JSONResult {     public string currency; } JSONResult res = (JSONResult) JSON.deserialize(jsonString, JSONResult.class); system.debug(res);   but of course I get an error that the identifier name is reserved.
17994
How can I deserialize this json object:      {     "response": {         "count": 1,         "benchmark": 0.22567009925842,         "requests": [             {                 "request": {                     "id": 537481,                     "image_thumbnail": "",                     "title": "Request for new bin(s) - residential",                     "description": "Propmain ref  3234-1114",                     "status": "submitted",                     "address": "36 Pine Tree Close",                     "location": "Peterborough, England",                     "zipcode": "PE1 1EJ",                     "user": "",                     "date_created": 1417173208,                     "count_comments": 0,                     "count_followers": 0,                     "count_supporters": 0,                     "lat": 52.599967,                     "lon": -0.233482,                     "user_follows": 0,                     "user_comments": 0,                     "user_request": 1,                     "rank": "0"                 }             }         ],         "status": {             "type": "success",             "message": "Success",             "code": 200,             "code_message": "Ok"         }     } }   What i've tried:   Map&lt;String,Object&gt; rawObj = (Map&lt;String,Object&gt;) JSON.deserializeUntyped(jsonString);     Map&lt;String,Object&gt; responseObj = (Map&lt;String,Object&gt;)rawObj.get('response');     List&lt;Object&gt; reqs = (List&lt;Object&gt;) responseObj.get('requests');     System.debug('Map Size = ' + reqs.size());     Map&lt;String, Object&gt; i = new Map&lt;String, Object&gt; ();     for (Object x : reqs) {          i = (Map&lt;String, Object&gt;)x; }     Map&lt;String,Object&gt; requests = (Map&lt;String,Object&gt;)i.get('request');     System.debug('Map Size = ' + i.size());     for (String field : i.keySet()){          Object id = i.get(field);         Object title = i.get('title');         System.debug('Id : ' + id);         System.debug('title : ' + title);          //System.debug('Title : ' + title);       }
109679
I have the following code:      public class OrderRequestCreationEmails {     public static void sendMail()     {          Messaging.reserveSingleEmailCapacity(2);         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();         String[] toAddresses = new String[] {'dgriff@varonis.com'};           mail.setToAddresses(toAddresses);          mail.setReplyTo('dgriff@varonis.com');          mail.setSenderDisplayName('Mail Test');          mail.setSubject('Success! Mail Sent');          mail.setBccSender(false);         mail.setPlainTextBody('BODY');          Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });     } }   I tried to call this function from a test as such: (I know its not an actual test, its just to see if I receive a mail).  @isTest private class CreationEmailsTest {     @isTest private static void sendMailTest() {         OrderRequestCreationEmails.sendMail();     } }   And I haven't received the mail, no idea why?  It's an example I took from the salesforce developer guide. couldn't find any answers online...  FYI - deliverability in the sandbox is turned on, and test deliverability works
117655
I have written a test class that covers 86% leaving out the apexpages.addmessage () in catch block, but majorly it throws the validation exceptions on that object when I try to update a record.(Here I am updating case status to closed and I have some custom fields to be filled out while closing the case).  My test class has 2 methods. 1st method is having the case with all the fields filled this covers all the code except catch block and 2nd method without the required fields while closing the case and even though it doesn't cover my test class to full 100%   In my case I am updating the case status to closed and while closing the case I have 2 custom fields that should not be "null" 1. xyz1__c and 2.xyz2__c (Their are validation rules written on the case object and these throwing me the exceptions if these fields are null while updating the case) I am not sure how to cover the validation exception in catch block in Test class   Can someone please provide any suggestions .  Apex controller  public with sharing class OCaseComment {     public String test2 {get;set;}     public String test1 {get;set;}     public string status {get;set;}     public casecomment ca;     public case c;     public ID caseId;     public pagereference save() {         caseId = ApexPages.currentPage().getParameters().get('caseid');         system.debug('case id entered' + caseId);         ca = new casecomment();         ca.ParentId = caseId;         ca.commentbody = 'question:' + test1 + '\n' + 'solution:' + test2;         ca.IsPublished = true;         list&lt;case&gt; c = [select Status, xyz1__c, xyz2__c from case where ID =: caseId];         list&lt;case&gt; cg = new list&lt;case&gt;();         for (case cd : c) {             cd.Status = 'Closed';             cg.add(cd);         }         try {             if (cg.size() &gt; 0 &amp;&amp; cg[0].xyz1__c != null &amp;&amp; cg[0].xyz2__c != null) {                 insert ca;             }             update cg;             status = 'saved';             system.debug('status value' + status);         } catch (DmlException d) {             Apexpages.addMessage(new ApexPages.message(Apexpages.Severity.Error, d.getMessage()));             status = 'unsaved';         }         return null;     } }   Test class   @isTest public class TestClassOCaseComment {     @isTest public static void withcaseid() {         case c = new         case (status = 'New', Origin = 'Phone', xyz1__c = 'Stats', xyz2__c = 'Issues');         insert c;         case ca = [select id, status, xyz2__c from             case where status = 'New'         ];         Test.setCurrentPage(page.SCaseComments);         OCaseComment cs = new OCaseComment();         cs.Test1 = ('test1');         cs.Test2 = ('test2');         apexpages.currentPage().getparameters().put('caseid', ca.id);         if (ca.id != null) {             cs.save();         }         casecomment cm = [select commentbody, isPublished from casecomment where parentid =: ca.Id];         string str = 'Question:' + cs.test1 + '\n' + 'Solution:' + cs.test2;         system.assertEquals(str, cm.CommentBody);         system.assert(true, cm.ispublished);         case g = [select Status from             case where ID = :                 ca.Id         ];         system.assertEquals('Closed', g.status);     }     @isTest static void caseWithoutproduct() {         try {             case c = new             case (status = 'New', Origin = 'Phone', xyz2__c = 'Issues');             insert c;             pagereference pr = page.SCaseComments;             pr.getParameters().put('caseid', c.Id);             test.setCurrentPage(pr);             OCaseComment cc = new OCaseComment();             cc.save();         } catch (Exception e) {             System.Assert(e.getMessage().contains('FIELD_CUSTOM_VALIDATION_EXCEPTION'));             System.Assert(e.getMessage().contains('xyz1__c'));         }     } }
27673
I've been lately trying to learn more and generally test Java's serialization for both work and personal projects and I must say that the more I know about it, the less I like it. This may be caused by misinformation though so that's why I'm asking these two things from you all:  1: On byte level, how does serialization know how to match serialized values with some class?  One of my problems right here is that I made a small test with ArrayList containing values "one", "two", "three". After serialization the byte array took 78 bytes which seems awfully lot for such low amount of information(19+3+3+4 bytes). Granted there's bound to be some overhead but this leads to my second question:  2: Can serialization be considered a good method for persisting objects at all? Now obviously if I'd use some homemade XML format the persistence data would be something like this  &lt;object&gt;     &lt;class="java.util.ArrayList"&gt;     &lt;!-- Object array inside Arraylist is called elementData --&gt;     &lt;field name="elementData"&gt;         &lt;value&gt;One&lt;/value&gt;         &lt;value&gt;Two&lt;/value&gt;         &lt;value&gt;Three&lt;/value&gt;     &lt;/field&gt; &lt;/object&gt;   which, like XML in general, is a bit bloated and takes 138 bytes(without whitespaces, that is). The same in JSON could be   {     "java.util.ArrayList": {         "elementData": [             "one",             "two",             "three"         ]     } }   which is 75 bytes so already slightly  smaller than Java's serialization. With these text-based formats it's of course obvious that there has to be a way to represent your basic data as text, numbers or any combination of both.  So to recap, how does serialization work on byte/bit level, when it should be used and when it shouldn't be used and what are real benefits of serialization besides that it comes standard in Java?
109364
I have a method which takes params object[] such as:  void Foo(params object[] items) {     Console.WriteLine(items[0]); }   When I pass two object arrays to this method, it works fine:  Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } ); // Output: System.Object[]   But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:  Foo(new object[]{ (object)"1", (object)"2" }); // Output: 1, expected: System.Object[]   How do I pass a single object[] as a first argument to a params array?