How We can Write Test Class for this Method.  public static String authMethod(){             Pardot_Credential_Setting__c objSetting = customSetting();              if(objSetting != null){                 String email = objSetting.Pardot_Email__c;                 String password = objSetting.Pardot_Password__c;                 String userKey = objSetting.User_Api_Key__c;                  HttpRequest req = new HttpRequest();                 req.setEndpoint( objSetting.Pardot_BaseUrl__c+'/api/login/version/4' );                 req.setMethod( 'POST' );                 req.setBody( 'email=' + email + '&amp;password=' + password + '&amp;user_key=' + userKey );                  HttpResponse res = new Http().send( req );                  System.debug('&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;res'+ res );                 System.debug('&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;res.getStatus()'+ res.getStatus() );                 System.debug('&gt;&gt;&gt;&gt;&gt;&gt;res.getBody()'+ res.getBody() );                  String response = res.getBody();                  Integer startIdx;                 Integer endIdx;                 String apiKey;                 if(response.contains('&lt;api_key&gt;')){                     startIdx = response.indexOf( '&lt;api_key&gt;' ) + 9;                     endIdx = response.indexOf( '&lt;/api_key&gt;' );                     apiKey = response.substring( startIdx, endIdx );                     System.debug( '&gt;&gt;&gt;&gt;&gt;&gt;&gt;apiKey'+ apiKey );                     return apiKey;                 }             }              return null;         }
15654
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.  How do I unit test code that includes a SOAP or REST-based callout, or indirectly calls code that makes a callout? I'm getting an error saying that callouts are not supported.
92770
Right now, I have code that looks something like this:  Private Sub ShowReport(ByVal reportName As String)     Select Case reportName         Case "Security"             Me.ShowSecurityReport()         Case "Configuration"             Me.ShowConfigurationReport()         Case "RoleUsers"             Me.ShowRoleUsersReport()         Case Else             pnlMessage.Visible = True             litMessage.Text = "The report name """ + reportName + """ is invalid."     End Select End Sub   Is there any way to create code that would use my method naming conventions to simplify things?  Here's some pseudocode that describes what I'm looking for:  Private Sub ShowReport(ByVal reportName As String)     Try         Call("Show" + reportName + "Report")     Catch ex As Exception         'method not found     End Try End Sub
84621
I'm struggling to test a class with pagereference. Following is the class...  public with sharing class redirectOrderPartner{  public String currentRecordId {get;set;} public orders__c orderId {get;set;}  public redirectOrderPartner(ApexPages.StandardController controller) {      }     Public Pagereference go(){      currentRecordId  = ApexPages.CurrentPage().getparameters().get('orderid');      system.debug('---currentRecordId  ---'+currentRecordId  );     orderId = [select id from orders__c where name =: currentRecordId limit 1];      system.debug('---orderid---'+orderId);      PageReference pageRef = new PageReference('/apex/OrderTrackingClass?id='+orderId.id);     pageRef.setRedirect(true);     return pageRef;    }   }   Following is what I tried....    @isTest  public class redirectOrderPartner_TEST  {             static testMethod void Test(){            Account acc = new Account(Name='ABC Corp.');           insert acc;            orders__c tempOrder = new orders__c(name = '0001234567', account__c = acc.id );           insert tempOrder;            Test.startTest();            PageReference pageRef = Page.redirectOrderPartner;           Test.setCurrentPage(pageRef);            ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(tempOrder);           ApexPages.currentPage().getParameters().put('Id',tempOrder.name);           PW_redirectOrderPartner ec = new redirectOrderPartner(sc);           ec.go();                                   Test.stopTest();       }   } I get the following error message on testing..     System.QueryException: List has no rows for assignment to SObject   What am I missing? Thanks
109516
I'm trying to use the HTTP Callout methods provided in Apex to  1. Get a token from Marketo 2. Use this token to create three leads in Marketo using the REST API  However, it doesn't seem to be working. I have never coded something like this before, so I expect that I probably made some very embarrassing and obvious mistakes, but I've been able to find very little documentation on this, so I'm starting from basically scratch and the REST API documentation. Anyways, here's the two classes I've been using to attempt to do this:  Class 1:  global class MakeCallouts {       static String testCallout() {          HttpResponse res = CalloutClass.getInfoFromExternalService();         String contentType = res.getHeader('Content-Type');         System.assert(contentType == 'application/json');         System.assertEquals(200, res.getStatusCode());      //getting the accesstoken       String getToken;     String answer = res.getBody();     System.debug(answer);  JSONParser parser = JSON.createParser(answer); while (parser.nextToken() != null) {     if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)){         String fieldName = parser.getText();         parser.nextToken();         if(fieldName == 'access_token') {            getToken = parser.getText();               }  } } System.debug(getToken);           HttpResponse res2 = CalloutClass.getInfoFromExternalService2(getToken);           String contentType2 = res2.getHeader('Content-Type');         System.assert(contentType2 == 'application/json');         System.assertEquals(200, res2.getStatusCode());          System.debug(res2.getBody());         return res2.getBody();     } }   Class 2:  public class CalloutClass {  public static HttpResponse getInfoFromExternalService () {     // Instantiate a new http object     Http h = new Http();       // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint     HttpRequest req = new HttpRequest();     req.setEndpoint('https://XXX-rlu-923.mktorest.com/identity/oauth/token?grant_type=client_credentials&amp;client_id=XXXX&amp;client_secret=XXXX');     req.setMethod('GET');      // Send the request, and return a response     HttpResponse res = h.send(req);     return res;  }   public static HttpResponse getInfoFromExternalService2 (String getToken) {     // Instantiate a new http object     Http h2 = new Http();       // Instantiate a new HTTP request, specify the method (POST) as well as the endpoint     HttpRequest req2 = new HttpRequest();     req2.setHeader('Content-Type','application/json');      req2.setMethod('POST');     req2.setEndpoint('https://XXXX.mktorest.com/rest/v1/leads.json?access_token='+getToken);     req2.setBody('{"action":"createOnly","input":[{"email":"kjashaedd-1@klooblept.com","firstName":"Kataldar-1","postalCode":"04828"},{"email":"kjashaedd-2@klooblept.com","firstName":"Kataldar-2","postalCode":"04828"},{"email":"kjashaedd-3@klooblept.com","firstName":"Kataldar-3","postalCode":"04828"}]}}');      // Send the request, and return a response     HttpResponse res2 = h2.send(req2);     return res2;  }    }   The MakeCallouts class is triggered when a Lead is created (this is entirely for testing purposes. I'm going to change the API call after I get this to work. But it's pretty obvious that the call is working when I see three new leads appear in my database, so it's a good test).
88408
I have this Visualforce code snippet in a page:  &lt;apex:outputLink value="javascript:if (window.confirm('Are you sure?')) DeleteQuoteLineItem('{!LineItem.QuoteLineItem.Id}');"&gt;     Del &lt;/apex:outputLink&gt;  &lt;apex:actionFunction action="{!DeleteQuoteLineItem}" name="DeleteQuoteLineItem" reRender="content"&gt;     &lt;apex:param value="test"/&gt; &lt;/apex:actionFunction&gt;   The two methods I'm using for testing are:  public void DeleteQuoteLineItem(String RecordID) {     System.debug('method with a paramater');     System.debug(RecordID); }  public void DeleteQuoteLineItem() {     System.debug('method without a parameter'); }   Everytime I click on the link to execute the apex:actionFunction, it's calling the DeleteQuoteLineItem() method without any parameter. I looked online and it seems like I need to create a class attribute and use assignTo= in my apex:param to populate it accordingly.  Is it possible to prevent this behavior and use standard method parameters, so I don't have to create class attributes? I want to work on a clean and optimized codebase, preventing unnecessary variable scope (so no class attribute when it's not required) and improve code re-usability by staying context agnostic.  Thanks
56847
This is an extension of .  So, using the answer from the previous question I mentioned, I am able to make a generic utility that would convert/parse an Enumeration to a String.  Now the only problem I have with my solution is, I can't seem to refactor the code to my liking. It works the way I want it to, but it is a tad more on the code heavy side than I had hoped for. I was curious if there was a design pattern (or any other way to code it) to help solve this issue. I am thinking there is a creational design pattern that will help in this case. I would be easy if I had lambda expression but, Apex is not quite there yet ;).  The code I use has kind of patterns dug into it already. It uses the Strategy, Factory, and Template(ish) pattern I believe. I have the resources to find something to solve this issue (my favorite Design Pattern books), but nothing I can think of jumps out at me.  Here is the code for my utility for just one enumeration:  private interface EnumerationToStringHelper {     List&lt;Object&gt; ProvideEnumerationValues();     Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue); }  private class ExampleEnumToStringHelper implements EnumerationToStringHelperExampleEnum {     public List&lt;Object&gt; ProvideEnumerationValues(){ return (List&lt;Object&gt;)ExampleEnum.values(); }     public Boolean CompareEnumerationToString(String possibleEnumeration, Object enumerationValue)     {         return  ((ExampleEnum)enumerationValue).name().equalsIgnoreCase(possibleEnumeration);     } }  private static Map&lt;Type, EnumerationToStringHelper&gt; TypeToEnumerationMap;  private static void PopulateTypeToEnumerationMap() {     TypeToEnumerationMap = new Map&lt;Type, EnumerationToStringHelper&gt;     {         Type.forName('ExampleEnum') =&gt; new ExampleEnumToStringHelper()     }; }  public static Object ConvertStringToEnumeration(Type enumerationType, String possibleEnumeration) {     if(possibleEnumeration == null) return null;     if(TypeToEnumerationMap == null)         PopulateTypeToEnumerationMap();      EnumerationToStringHelper conversionAction = TypeToEnumerationMap.get(enumerationType);      if(conversionAction == null)         throw new EnumerationToStringException('The Type you enter is either a) not an enumeration or b) not a supported enumeration.');      for(Object particalarEnumValue : conversionAction.ProvideEnumerationValues())         if(conversionAction.CompareEnumerationToString(possibleEnumeration, particalarEnumValue))             return particalarEnumValue;     return null; }   public class EnumerationToStringException extends Exception { }   Now in order to use the utility, it is exactly what I hoped for.  return (ExampleEnum)RT_GeneralUtilities.ConvertStringToEnumeration(Type.forName('ExampleEnum'), 'Testing');   It is a little long, but it beats having the entire for loop for 12 or more different Enum types. That is why I wanted to build the utility - essentially for better readability and test coverage purposes.  The downside with this is I have to make a helper for every single Enum type. So it makes it kind of an eyesore maintainability-wise.    I was hoping there was a pattern I could implement to assuage that eyesore and make it appealing on both sides. Any suggestions?
120241
I'm using data faker and I would like to know how to make my variables available in all steps of my test.  I wanted to leave all elements mapped in the initial step, or be given  WebDriver driver = new ChromeDriver();     //Mapping the elements  WebElement nomeusuario = driver.findElement(By.className("whsOnd zHQkBf"));   My main code is:  public class Criar_Conta_Gmail {  @Given("^que eu esteja na pagina principal do gmail\\.$") public void que_eu_esteja_na_pagina_principal_do_gmail() throws Throwable {     System.setProperty("webdriver.chrome.driver","C:\\Browsers\\chromedriver.exe");     WebDriver driver = new ChromeDriver();     driver.get("https://www.gmail.com");     driver.findElement(By.xpath("//span[contains(text(),'Criar conta')]")).click();     Thread.sleep(2000);     driver.findElement(By.xpath("//div[contains(text(),'Para mim')]")).click();     throw new PendingException();   }  @When("^criar uma nova conta com telefone invalido\\.$") public void criar_uma_nova_conta_com_telefone_invalido() throws Throwable {         WebDriver driver = new ChromeDriver();         //Mapping the elements      WebElement nomeusuario = driver.findElement(By.className("whsOnd zHQkBf"));      // sending data to the application     Faker faker = new Faker();     String Nome = faker.name().firstName();     nomeusuario.sendKeys(Nome);      throw new PendingException(); }  @Then("^o sistema não permite a finalização do cadastro\\.$") public void o_sistema_não_permite_a_finalização_do_cadastro() throws Throwable  {     // Write code here that turns the phrase above into concrete actions     throw new PendingException(); }
115021
Ideally, I'd like to write a unit test to help me "dummy check" for unexpected effects of the upcoming guest user sharing setting changes.  We'd had some controller/trigger code "gracefully handling" data it couldn't see thanks to the new sharing restrictions ... which resulted in simply "not doing" some work that it was supposed to do, which from a business process perspective isn't "graceful" at all (it was an important automation for downstream processes).  I'd like to write up a unit test with some system.assert statements validating that "data still goes where it's supposed to" when the "submit" button a public-facing Visualforce page of a community is clicked.  Unfortunately, I can't seem to make the "submit" button on a Controller for a public-facing Visualforce page work in the context of a unit test because the record whose creation it results in doesn't get its corresponding "sharing setting" record created in time for the execution context to pick it up.  I did a little proof of concept here ...  @isTest public class TestClass {      private static Id guestProfileId = Util.getProfileIdByName('Public Facing Portal Profile');     private static User guestUser;     private static Id portalGroupId = [SELECT Id FROM Group WHERE Name = 'Public_Portal' LIMIT 1][0].Id;      private static Custom_Object__c co;       private static testMethod void runTest() {         createCO();         Test.startTest();         // Note that putting createCO() inside the test and doesGuestSharingRuleExistForCO() doesn't help.         // That's what I was afraid of.         try {             doesGuestSharingRuleExistForCO(co.Id);         }         catch (Util.DeveloperException e) {             System.assert(FALSE, e.getMessage());         }         Test.stopTest();     }       private static void cacheUsers() {         guestUser = [SELECT Id FROM User WHERE profileid = :guestProfileId AND IsActive = TRUE LIMIT 1][0];     }      private static void createCO() {         co = new Custom_Object__c();         INSERT co;     }      private static void doesGuestSharingRuleExistForCO(Id coId) {         List&lt;SObject&gt; existingSharingRulesOnCO = [             SELECT Id FROM Custom_Object__share             WHERE RowCause = 'GuestRule' AND AccessLevel = 'Read' AND ParentId = :coId AND UserOrGroupId = :portalGroupId LIMIT 1         ];         if ( existingSharingRulesOnCO.isEmpty() ) { throw new Util.DeveloperException('Guest User sharing is not on for this custom object ID'); }     }      private static Boolean isCOSharingFlippedOnAtAll(){         String lookingFor = 'Custom_Object__Share';         for (Schema.SObjectType sObjectType : Schema.getGlobalDescribe().values() ) {             String sobjName = String.valueOf(sObjectType);             if (sobjName.contains(lookingFor) ) { return TRUE; }         }         return FALSE;     }  }   Am I just out of luck?  Is there no way to properly unit-test the effects (to automations relying upon "guest user" sharing settings when running as "guest user") of simulating the insertion of records into my database from a Visualforce page, due to not being able to separate out "execution context" enough and "wait" for the sharing rule record for the new record to come into existence?
77080
This may sound repititve question. But the error incurs after following multiple links found like:  and .  The controller:  public with sharing class SFLoginCtrlr {     public static HTTPResponse getResp(String loginCred){         Map&lt;String, Object&gt; mapLoginCred = (Map&lt;String, Object&gt;)JSON.deserializeUnTyped(loginCred);         String username = ''+mapLoginCred.get('username');         String password = ''+mapLoginCred.get('password');         HttpRequest req = new HttpRequest();         req.setMethod('POST');            req.setTimeout(60000);         req.setEndpoint('https://www.salesforce.com/services/Soap/u/29.0');         req.setHeader('Content-Type', 'text/xml;charset=UTF-8');                 req.setHeader('SOAPAction', '""');         req.setBody('&lt;Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;Header/&gt;&lt;Body&gt;&lt;login xmlns="urn:partner.soap.sforce.com"&gt;&lt;username&gt;' +username+ '&lt;/username&gt;&lt;password&gt;' + password + '&lt;/password&gt;&lt;/login&gt;&lt;/Body&gt;&lt;/Envelope&gt;');                 HttpResponse res = new Http().send(req);         return res;     } }   The mock class:  @isTest global class ExampleCalloutMock implements HttpCalloutMock{   global HttpResponse respond(HTTPRequest req){     HttpResponse res = new HttpResponse();     res.setStatus('OK');     res.setStatusCode(200);     res.setBody('SUCCESS');     return res;   } }   The test class:  @isTest private class SFLoginCtrlrTest{     static testMethod void SFLoginCtrlrTestMethod(){         Test.startTest();          Test.setMock(HttpCalloutMock.class, new ExampleCalloutMock());          Map&lt;String, String&gt; logincred = new Map&lt;String, String&gt;();         logincred.put('username', 'dummy@user.com');         logincred.put('password', 'notapassword');          SFLoginCtrlr.getResp(JSON.serialize(logincred));          Test.stopTest();     } }   The error received while running test class:     Methods defined as TestMethod do not support Web service callouts   Not sure, where is the issue...
82873
I am trying to learn how to do APEX testing but all the tests in the documentation are too complex and I can't find an example of a simple APEX Controller that is a Hello World Test.  I have this APEX Code  public class MessageMaker{ public static string helloMessage() {     return('You say "Goodbye," I say "Hello"');     } }   Should I be testing that the String is the same? Here is my test that doesn't work      @isTest public class MessageMakerTest {     public static testMethod void testMyClass(){         MessageMaker controller = new MessageMaker();         String helloMessage = helloMessage();          System.assertEquals(helloMessage, 'You say "Goodbye," I say "Hello"');      } }   I am getting this error.       Method does not exist or incorrect signature: helloMessage()   I have some more advanced APEX code but I want to understand what I need to test for and how before I can do that.  Thank you in advance.
9792
Yesterday I had a two-hour technical phone interview (which I passed, woohoo!), but I completely muffed up the following question regarding dynamic binding in Java.  And it's doubly puzzling because I used to teach this concept to undergraduates when I was a TA a few years ago, so the prospect that I gave them misinformation is a little disturbing...  Here's the problem I was given:  /* What is the output of the following program? */  public class Test {    public boolean equals( Test other ) {     System.out.println( "Inside of Test.equals" );     return false;   }    public static void main( String [] args ) {     Object t1 = new Test();     Object t2 = new Test();     Test t3 = new Test();     Object o1 = new Object();      int count = 0;     System.out.println( count++ );// prints 0     t1.equals( t2 ) ;     System.out.println( count++ );// prints 1     t1.equals( t3 );     System.out.println( count++ );// prints 2     t3.equals( o1 );     System.out.println( count++ );// prints 3     t3.equals(t3);     System.out.println( count++ );// prints 4     t3.equals(t2);   } }   I asserted that the output should have been two separate print statements from within the overridden equals() method: at t1.equals(t3) and t3.equals(t3).  The latter case is obvious enough, and with the former case, even though t1 has a reference of type Object, it is instantiated as type Test, so dynamic binding should call the overridden form of the method.  Apparently not.  My interviewer encouraged me to run the program myself, and lo and behold, there was only a single output from the overridden method: at the line t3.equals(t3).  My question then is, why?  As I mentioned already, even though t1 is a reference of type Object (so static binding would invoke Object's equals() method), dynamic binding should take care of invoking the most specific version of the method based on the instantiated type of the reference.  What am I missing?
7725
I'm building a class library that will have some public &amp; private methods. I want to be able to unit test the private methods (mostly while developing, but also it could be useful for future refactoring).  What is the correct way to do this?
15516
I have some code that raises PropertyChanged events and I would like to be able to unit test that the events are being raised correctly.  The code that is raising the events is like  public class MyClass : INotifyPropertyChanged {    public event PropertyChangedEventHandler PropertyChanged;       protected void NotifyPropertyChanged(String info)    {         if (PropertyChanged != null)         {             PropertyChanged(this, new PropertyChangedEventArgs(info));         }    }       public string MyProperty    {        set        {            if (_myProperty != value)            {                _myProperty = value;                NotifyPropertyChanged("MyProperty");            }        }    } }   I get a nice green test from the following code in my unit tests, that uses delegates:  [TestMethod] public void Test_ThatMyEventIsRaised() {     string actual = null;     MyClass myClass = new MyClass();      myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)     {          actual = e.PropertyName;     };      myClass.MyProperty = "testing";     Assert.IsNotNull(actual);     Assert.AreEqual("MyProperty", actual); }   However, if I then try and chain the setting of properties together like so:  public string MyProperty {     set     {         if (_myProperty != value)         {             _myProperty = value;             NotifyPropertyChanged("MyProperty");             MyOtherProperty = "SomeValue";         }     } }  public string MyOtherProperty {     set     {         if (_myOtherProperty != value)         {             _myOtherProperty = value;             NotifyPropertyChanged("MyOtherProperty");         }     } }   My test for the event fails - the event that it captures is the event for the MyOtherProperty.  I'm pretty sure the event fires, my UI reacts like it does, but my delegate only captures the last event to fire.  So I'm wondering: 1. Is my method of testing events correct? 2. Is my method of raising chained events correct?
49085
I am facing difficulty in passing parameters to apex method from test method. In apex method, I am getting parameters from my VF page. Example of Apex Method: public PageReference create_contact()  {         String callfrom = System.currentPageReference().getParameters().get('callfrom');                  Contact newCon = new Contact(lastname = 'Anonymous', phone = callfrom);           insert newCon;                  return null; }  My Test method: static testMethod void testmatchingcontactController() {         test.startTest();         matching_contacts mc = new matching_contacts();         mc.create_contact();         test.stopTest(); }  On running test method, I get an error that &quot;Argument cannot be null&quot; because the parameter callfrom in apex code is provided by Visualforce page in application. I don't know how can I pass it from test method. Please help if you know solution to this problem.
61619
I'm new to TDD and xUnit so I want to test my method that looks something like:   List&lt;T&gt; DeleteElements&lt;T&gt;(this List&lt;T&gt; a, List&lt;T&gt; b);   Is there any Assert method that I can use ? I think something like this would be nice  List&lt;int&gt; values = new List&lt;int&gt;() { 1, 2, 3 }; List&lt;int&gt; expected = new List&lt;int&gt;() { 1 }; List&lt;int&gt; actual = values.DeleteElements(new List&lt;int&gt;() { 2, 3 });  Assert.Exact(expected, actual);   Is there something like this ?
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);     } }
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'));         }     } }