i have written a class i am trying get test coverage. i have written below. Could you please help me here  Class :  public class WrapperCam   {      public Boolean check{get;set;}     public Campaign Cmp{get;set;}      public WrapperCam(Id Idcc,String Nme)     {         this.check=false;         this.Cmp = new Campaign(Id=Idcc,Name=Nme); } }   Test class:  @isTest  Public class WrapperCamtest {   @testSetup    static void setupTestData(){      test.startTest();      Campaign campaign_Obj = new Campaign(id='00001',Name = 'suresh');      Insert campaign_Obj;       test.stopTest();   } }   Let me know what should i add here so that i get 100% coverage  Thanks in advance!
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?
106424
Should Coded UI tests be within the solution that they are testing (similar to Unit Tests), or should they be contained in a separate, generic Coded UI solution that is built only once and executed whenever any solution needs to be tested? I should clarify that our Coded UI tests are not the regular recordings that can be created through Visual Studio, but rather hand-coded interaction classes developed by our QA engineers. Most of the common functions for interacting with elements on a page are packaged into a DLL that can be referenced in any test.  I'm basically just trying to find out what the best practice is for creating a Coded UI testing infrastructure. Any help would be greatly appreciated. Thanks!
56738
In Field Service Lightning I have a Trigger on ServiceReport which sends an email with attachment coming from ContentVersion.   This is the Test class I have written.  @isTest  private class testCreateServiceReport{       static testMethod void validateWO() {       WorkOrder wo = new WorkOrder();       wo.subject = 'Testing';       insert wo;       ServiceAppointment sa = new ServiceAppointment();       sa.ParentRecordId = wo.Id;       sa.EarliestStartTime = DateTime.now();       sa.DueDate = DateTime.now();       insert sa;       List&lt;ServiceReportLayout&gt; srl = [Select Id FROM ServiceReportLayout];       ServiceReport sr = new ServiceReport();       sr.ParentId = sa.Id;       sr.Template = srl[0].Id; //Need to check if there is a way to avoid srl[0] notation       insert sr; //If I comment this the text result is pass. When I enable it I get too see the below mentioned error.  }  }   This is the error Methods defined as TestMethod do not support Web service callouts I know that we need to write Test Classes for code that involves web service callouts using setMock() but I dont understand in what way inserting ServiceReport is related to making a callout.  Any help on this will be really helpful.
93772
below is my code Created a wrapper class like below  public class ResponseWrapper{     public list&lt;Account&gt; lstaccounts;     public boolean isError ;     public string errorCode;     public integer statusCode;        public ResponseWrapper(){          lstaccounts = new list&lt;Account&gt;();          isError= false;     }  }   and returning the wrapper class in the Httpget method  @RestResource(urlMapping='/accounts/*') global with sharing class AccountRestService { @HttpGet global static ResponseWrapper getAccounts() {     ResponseWrapper resWrap = new ResponseWrapper();     List&lt;Account&gt; accounts;      try {         accounts = [SELECT Id, Name FROM Account];         res.lstaccounts = accounts;     } catch (Exception e) {         RestResponse res = RestContext.response;         resWrap.isError = true;         res.responseBody = Blob.valueOf(e.getMessage()) = resWrap.errorCode;         res.statusCode = 500 = resWrap.statusCode;     }      return resWrap;   } }   but its throwing the Error message  Error: Compile Error: global methods do not support return type of ResponseWrapper at line 4 column 31
18034
when i try to save the following code, i got the error below. Following same instructions given in this link, but still errors. Am i doing anything wrong here? please suggest.    @isTest private class WebSvcCalloutTest {     @isTest static void testEchoString() {         Account a = new Account(name='Tester',SAP_KUNNR__c='1172');         insert a;                       // This causes a fake response to be generated         Test.setMock(WebServiceMock.class, new WebServiceMockImpl());      } }   Error:  Save error: Method does not exist or incorrect signature: Test.setMock(Type, WebServiceMockImpl)    WebSvcCalloutTest.cls         @isTest global class WebServiceMockImpl implements WebServiceMock {    global void doInvoke(            Object stub,            Object request,            Map&lt;String, Object&gt; response,            String endpoint,            String soapAction,            String requestName,            String responseNS,            String responseName,            String responseType) {          sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00 sap1 = new sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00();                Map&lt;String,String&gt; mapSAP = new Map&lt;String,String&gt; {};         sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01 req = new sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01();               sapComDocumentSapSoapFunctionsMcS.ZGssmwfmHndlEvntrqst00Response_element ret =  sap1.ZGssmwfmHndlEvntrqst00('',req);         response.put('response_x', ret);     } }
5058
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 do I start writing my first unit test?  How do I unit test this code?  I need help writing this unit test.   Salesforce Stack Exchange looks for detailed, specific questions that the community can help you with, and can't write tests on your behalf. We feel that working with the resources below can help you get started, and we encourage you to make an attempt to write your test and return to SFSE with your specific questions when you encounter challenges you can't resolve.
6142
Is there anyway to get Eclipse to automatically look for static imports? For example, now that I've finally upgraded to Junit 4, I'd like to be able to write:  assertEquals(expectedValue, actualValue);   hit Ctrl + Shift + O and have Eclipse add:  import static org.junit.Assert.assertEquals;   Maybe I'm asking too much.
30151
How can the Test Coverage can be fulfilled for the Apex classes which queried for External Objects.I have written Test class just like assuming External Object behaves like a custom Object but getting error repetitively "CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: You can't create records for the object".  I used the DML statements like Database.insertAsync but no use. Gone through some articles saying that we need to mock the external object for the Apex Test coverage on External Object. If so is there document which explains about this concept.
82927
How do you make a test class for custom controller? My search results involves this but trying to apply it in my test class only create too many error that I don't understand.  public static testMethod void testMyController() {     PageReference pageRef = Page.success;//Observe how we set the Page here     Test.setCurrentPage(pageRef);   . Does my test class need those line of codes when my controller class is only very simple.  public class ClientInfo_VFcontroller{     public Org_Info__c orgInfo {get; set;}     public ClientInfo_VFcontroller(){         orgInfo = new Org_Info__c();     }     public PageReference save(){         insert orgInfo;         orgInfo = null;         ScheduleRetrieve.ScheduleRetrieve();         return null;     } }
14935
Is there a way to test code coverage within visual studio if I'm using MSTest? Or do I have to buy NCover?   Is the NCover Enterprise worth the money or are the old betas good enough if Microsoft doesn't provide built in tools to do code coverage?  EDIT: Description of VS Products and which ones include code coverage   TestDriven.NET () can be used if your VS version doesn't support it.
4709
I am preparing for a testing certification. These types of questions are asked frequently.  Example 1: Read P Read Q IF P+Q &gt; 100 THEN Print “Large” ENDIF If P &gt; 50 THEN Print “P Large” ENDIF   Example 2:  READ X  READ Y  I F X&gt;Y THEN Z = 0  ENDIF   Example 3: 1 READ X  2 READ Y  3 Z =X + 2*Y  4 IF Z&gt; 50 THEN  5 PRINT large Z  6 ENDIF     What are Nodes and Edges in the flowchart?  Statement Coverage: 1A-2C-3D-E-4G-5H = 1 Branch Coverage: 1A-2C-3D-E-4G-5H , 1A-2B-E-4F = 2 Path Coverage: 4 1A-2B-E-4F 1A-2B-E-4G-5H 1A-2C-3D-E-4G-5H 1A-2C-3D-E-4F   Please explain , how the answers came by?  In these example, how do we identify that which is a statement, branch and condition? How do we measure coverage? Please give detailed explanations of ALL 3 examples.
48842
I'm creating my first full framework using Selenium and TestNG and recently implemented the ability to have logging enabled which will track every action (before and after).  public class CustomLogs {     //Set Logging_Level to "Debug" to enable logging     public String Logging_Level = "OFF";      public void Log(String message) {         if (Logging_Level == "Debug")         {System.out.println(message);         } else {         }     } }   Then, in my page objects, EVERY action method has a log statement before and after EVERY action.  public class LoginPage extends BrowserConfig {      final WebDriver driver;     private static CustomLogs customlogs = new CustomLogs();      //Elements on Page     @FindBy(id = "userId")     private WebElement userNameField;      //Constructor     public LoginPage(WebDriver driver) {         this.driver = driver;     }      //Fill Username     public void FillUsername(String userNameEntry) {         userNameField.clear();         customlogs.Log("Entering Username: "+userNameEntry+"...");         userNameField.sendKeys(userNameEntry);         customlogs.Log("Username entered.");   It seems like this is very beneficial, not only for debugging, but also because you can now print out every single action step, so keeping records or showing others what steps were completed is very straightforward.  But I can also see how this is cluttering the page object code.  Is this a good idea?  And/or is there a better way to do this?
27158
I run the test class and try to capture the permission set name in debug. But i got Id than name. Any reason why I am getting this ? Please help me to understand.  See the image, what i query in return what i got !
18923
I am trying to write a test for a trigger that is firing a future apex callout :  The trigger calls the callBillingService method from this class:  public class BillingCalloutService {     //Implement business and callout logic methods here     @Future(callout=true)     public static void callBillingService(List&lt;Id&gt; recordIds) {         List&lt;Project__c&gt; projects = [Select Id, ProjectRef__c,Billable_Amount__c from Project__c Where Id = :recordIds];          List&lt;Project__c&gt; projectsToUpdate = new List&lt;Project__c&gt;();          String username = ServiceCredentials__c.getValues('BillingServiceCredential').Username__c;         String password = ServiceCredentials__c.getValues('BillingServiceCredential').Password__c;          String auth = username + ':' + password;         String encodedAuth = EncodingUtil.base64Encode(Blob.valueOf(auth));          for(Project__c p : projects) {              BillingServiceProxy.InvoicesPortSoap11 service = new BillingServiceProxy.InvoicesPortSoap11();             service.inputHttpHeaders_x = new Map&lt;String, String&gt;();             service.inputHttpHeaders_x.put('Authorization', 'Basic ' + encodedAuth);              BillingServiceProxy.project project = new BillingServiceProxy.project();             project.username = username;             project.password = password;             project.projectRef = p.ProjectRef__c;             project.billAmount = p.Billable_Amount__c;              if(service.billProject(project).equals('ok')){                 projectsToUpdate.add(new Project__c(ProjectRef__c = p.ProjectRef__c, Status__c = 'Billed'));             }         }         shouldIRun.stopTrigger();         upsert projectsToUpdate ProjectRef__c;     } }   Error     Methods defined as TestMethod do not support Web service callouts   Test Class  @IsTest private class BillingCalloutServiceTest {      @IsTest     private static void testBillingCalloutService() {     Account a = new Account(Name = 'Acme');     insert a;     Opportunity o = new Opportunity(Name='Test', StageName='Submitted Project', AccountId=a.Id, Amount=1000, CloseDate=Date.Today());     insert o;     Project__c p = new Project__c(Status__c='Running',Start_Date__c=Date.Today(),End_Date__c=Date.Today(),Billable_Amount__c=10000,ProjectRef__c='projectX',Opportunity__c=o.Id);     insert p;      insert new ServiceCredentials__c(Name='BillingServiceCredential',Username__c='toto', Password__c='azerty');      Test.startTest();     Test.setMock(HttpCalloutMock.class, new BillingCalloutServiceMock());       p.Status__c = 'Billable';       update p;     Test.stopTest();     // runs callout and check results     p = [select Status__c from Project__c where id =: p.id];     System.assertEquals('Billed', p.Status__c);     }  }
86355
My team is responsible for the development of an API for a large system that we also write. We need to provide example code so that other developers using our API can learn how to use it. We have been documenting the code using the xml document comments. eg.  /// &lt;summary&gt;Summary here&lt;/summary&gt; /// &lt;example&gt;Here is an example  &lt;code&gt;example code here&lt;/code&gt; &lt;/example&gt; public void SomeFunction()    We then use Sandcastle and build the help files we need (chm and an online website).  It is quite embarrassing when the example code doesnt work, and this is usually because some functionality has changed or a simple error.  Has anyone ever done something like this, but also configured unit tests to run on the example code so that they are known to work during the build?
44663
I have inherited an org with lots of outdated apex, and multiple changes to VRs, field requirements, field values, profile names, record type names etc. All of this was done without any insight into, or konwledge of, apex that had also been written many years ago.   Production code coverage is now hovering around 40%......   Most of the existing custom apex is now irrelevant (outdated processes that are no longer used) and I need to get coverage up so I can begin to push change sets and update the existing org.   Since my primary goal is to raise code coverage and then delete many of the existing classes, triggers, extensions, etc  my question is: Can I simply replace existing class code with simpler classes and test classes rather than dig through and update the existing code and configuration?  Again, the goal is to get rid of a lot of this code anyway so this seems like a quick and dirty solution to an otherwise overwhelming problem.   Any thoughts?
11325
I have written a test class for a trigger on the lead object.  When i run the test class i get the following error:  Methods defined as TestMethod do not support Web service callouts, test skipped  There is an other trigger on lead that has a call to a webservice so i get this error.  I have wrapped the call with:  if (!Test.isRunningTest()) {    // do callout }   But i’m still getting the same error.  Any other way to run correctly the test class?  Thank you in advantage.