I have several unit tests that I'm working on for an api. The tests use @patch to mock the api calls. Some of the tests I wish to create should trigger exceptions. How do I handle that in a unit test?  Here's what I have so far. Pylint complains about the assertTrue() statements. I'm sure there's a better way to handle exceptions.  @patch('myapi.myapi.requests.request') def test_auth_failure(self, mock_request):     # Configure the request mock to return an auth failure     # Auth/login (/session) failures return status 200, but without a token!     mock_request.return_value.status_code = 200     mock_request.return_value.content = json.dumps(self.mock_auth_failure)     try:         # Call auth()         self.api.auth()         # Exception should have been raised         self.assertTrue(False)     except exceptions.HTTPUnauthorized:         # Exception caught         self.assertTrue(True)   Additional Information: This is in a class extending from unittest.TestCase. Example:   class MyApiTests(unittest.TestCase):
4542
How does one write a unittest that fails only if a function doesn't throw an expected exception?
5626
I'm trying to write test code for a Batchable class that AllowsCallouts.  I've written a lot of other test code that uses HttpCalloutMock classes, and planned to do so for this class as well.  And, per best practices, I'm setting up my test data before calling Test.startTest().  Even so, I get a CalloutException:     System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out   This somewhat makes sense, because my start() method passes a SOQL query to Database.getQueryLocator() and my execute() method makes the web callouts.  I'm guessing that when my test method calls test.stopTest(), both start() and execute() run in the same context.  In regular batch operation, they happen in separate contexts so there isn't any uncommitted work.  I intend to work around this by calling the methods directly, possibly even calling start() before Test.startTest(), and then using the returned Database.QueryLocator to get the list of records I'll pass into execute().  I don't like the fact that I'm not testing the batch size used by the static method that kicks off the batch with Database.executeBatch(), so I'll probably have that use a constant that I can reference from my test code to ensure it's using the same batch size.  Salesforce kind of addresses this in the "Asynchronous Apex and Mock Callouts" section of the , but they don't make reference to Batchable classes with Callouts.  They only talk about making callouts and testing Batchable classes in the same test method.  So, my question is whether there is a better way to write this test.  I'm also throwing this out so others searching the site can learn about possible workarounds.
5057
I have a child form that is throwing an ApplicationException in the Load event handler (intentionally for testing purposes).  The parent form wraps the ChildForm.Show() method in a Try...Catch ex As Exception block.  The catch block simply displays a message and closes the child form.  All works as expected when debugged in visual studio 2008 (.net 3.5 sp1).  However, when I run it outside of visual studio, the Catch block seems to get missed and an unhandled exception occurs.  Any idea why that is?  Thank you.  Example Code:  Public Class Form1      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click         Dim f2 As Form2          f2 = New Form2          Try             MessageBox.Show("Opening form 2")             f2.ShowDialog()         Catch ex As Exception             f2.Close()             MessageBox.Show("Form 2 closed.")         End Try     End Sub  End Class  Public Class Form2      Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load         Throw New ApplicationException("Test Form_Load")     End Sub      Public Sub New()          ' This call is required by the Windows Form Designer.         InitializeComponent()          ' Add any initialization after the InitializeComponent() call.     End Sub  End Class   Stack Trace:    System.ApplicationException:  Test Form_Load   at WindowsApplication1.Form2.Form2_Load(Object sender, EventArgs e)  in UnhandledExceptionTest2\WindowsApplication1\Form2.vb  System.Windows.Forms.Form.OnLoad(EventArgs e)  System.Windows.Forms.Form.OnCreateControl()  System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)  System.Windows.Forms.Control.CreateControl()  System.Windows.Forms.Control.WmShowWindow(Message& m)    at  System.Windows.Forms.Control.WndProc(Message&> m)    at  System.Windows.Forms.ScrollableControl.WndProc(Message&> m)    at  System.Windows.Forms.ContainerControl.WndProc(Message&> m)    at  System.Windows.Forms.Form.WmShowWindow(Message&> m)    at  System.Windows.Forms.Form.WndProc(Message&> m)    at  System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&> m)    at  System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&> m)    at  System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr  lparam)
89923
Question:  Is exception handling in Java actually slow?  Conventional wisdom, as well as a lot of Google results, says that exceptional logic shouldn't be used for normal program flow in Java.  Two reasons are usually given,   it is really slow - even an order of magnitude slower than regular code (the reasons given vary),     and    it is messy because people expect only errors to be handled in exceptional code.     This question is about #1.  As an example,  describes Java exception handling as "very slow" and relates the slowness to the creation of the exception message string - "this string is then used in creating the exception object that is thrown. This is not fast."  The article  says that "the reason for this is due to the object creation aspect of exception handling, which thereby makes throwing exceptions inherently slow".  Another reason out there is that the stack trace generation is what slows it down.  My testing (using Java 1.6.0_07, Java HotSpot 10.0, on 32 bit Linux), indicates that exception handling is no slower than regular code.  I tried running a method in a loop that executes some code.  At the end of the method, I use a boolean to indicate whether to return or throw.  This way the actual processing is the same. I tried running the methods in different orders and averaging my test times, thinking it may have been the JVM warming up.  In all my tests, the throw was at least as fast as the return, if not faster (up to 3.1% faster).  I am completely open to the possibility that my tests were wrong, but I haven't seen anything out there in the way of the code sample, test comparisons, or results in the last year or two that show exception handling in Java to actually be slow.  What leads me down this path was an API I needed to use that threw exceptions as part of normal control logic.  I wanted to correct them in their usage, but now I may not be able to.  Will I instead have to praise them on their forward thinking?  In the paper , the authors suggest that the presence of exception handlers alone, even if no exceptions are thrown, is enough to prevent the JIT compiler from optimizing the code properly, thus slowing it down.  I haven't tested this theory yet.
105415
This is the test method i have writtenfor batch apex ProductUpdate  .Even if i have a single callout to Database.Executebatch()  I am getting the following error.  Please help !  @isTest (seeAllData=true) global class testbatchProductUpdate  {     public static testMethod  void  pBatchUpdate()     {          /** Product to meet the Criteria in test class **/          Product2 p = new Product2();         p.Name = 'Test Product';         p.Effective_Date__c = Date.Today();         //p.CurrencyIsoCode= 'USD';         p.Material_status__c='status';         insert p;          /** Product to meet the Criteria in test class **/           test.startTest();         batchProductUpdate bpu = new batchProductUpdate();         database.Executebatch(bpu);         test.stopTest();     }  }      Error :  System.UnexpectedException: No more than one executeBatch can be called from within a testmethod. Please make sure the iterable   returned from your start method matches the batch size, resulting in   one executeBatch invocation.", Failure Stack Trace: "External entry   point"
9169
I want to see the stack trace in any function of my code, so i made somthing like this to call it and print the stack trace:  public function PrintStackTrace() {     try {         throw new Error('StackTrace');     } catch (e:Error) {         trace(e.getStackTrace());     } }   I like to know if there are other way to do this. In some place, the Error class creates the stack trace, but maybe it didn't do it with ActionScript 3.0 so maybe it's not posible, but i want to know.  Thanks!
30789
It is my understanding that I can test that a method call will occur if I call a higher level method, i.e.:  public abstract class SomeClass() {         public void SomeMehod()     {         SomeOtherMethod();     }      internal abstract void SomeOtherMethod(); }   I want to test that if I call SomeMethod() then I expect that SomeOtherMethod() will be called.   Am I right in thinking this sort of test is available in a mocking framework?
89434
I am calling, through reflection, a method which may cause an exception. How can I pass the exception to my caller without the wrapper reflection puts around it? I am rethrowing the InnerException, but this destroys the stack trace. Example code:  public void test1() {     // Throw an exception for testing purposes     throw new ArgumentException("test1"); }  void test2() {     try     {         MethodInfo mi = typeof(Program).GetMethod("test1");         mi.Invoke(this, null);     }     catch (TargetInvocationException tiex)     {         // Throw the new exception         throw tiex.InnerException;     } }
98616
I can hookup to AppDomain.CurrentDomain.UnhandledException to log exceptions from background threads, but how do I prevent them terminating the runtime?
36362
My question is what do most developers prefer for error handling, Exceptions or Error Return Codes. Please be language(or language family) specific and why you prefer one over the other.  I'm asking this out of curiosity. Personally I prefer Error Return Codes since they are less explosive and don't force user code to pay the exception performance penalty if they don't want to.  update: thanks for all the answers! I must say that although I dislike the unpredictability of code flow with exceptions. The answer about return code (and their elder brother handles) do add lots of Noise to the code.
103721
Here is the code  global class DeleteRjectedQuote implements Database.Batchable{     global Database.QueryLocator start(Database.BatchableContext BC){         return Database.getQueryLocator([select id,Status from Case where Status='Escalated']);     }     global void execute(Database.BatchableContext BC,list lstcase){          if(!lstcase.isEmpty()){             delete lstcase;         }      }     global void finish(Database.BatchableContext BC){ }  }   test class:: i have gone through trailhead but I am getting 0 codecoverage. How can we increase code coverage::                                                                                       @isTest public class TestDeleteRjectedQuote {     @isTest static void testDeleteRjectedQuotemethod(){         Test.startTest();         Case qt = new Case();         qt.status = 'escalated';         insert qt;            DeleteRjectedQuote drq = new DeleteRjectedQuote();         database.executeBatch(drq);         Test.stopTest();     } }
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.
20064
I have written below Wrapper class.  global class BI_VA_AutomationWrapper {      global class BI_VA_AutomationRequest {      webservice String userName;     webservice String emailId;     webservice String buinessUnit;     webservice String orgName;     webservice String country;     webservice String environment;     webservice String myShopNumber;     webservice String BidsId;//for testing     webservice String Type; //for testing  }  global class BI_VA_AutomationResponse {      webservice String responseStatus;     webservice String myShopNumber;     //webservice list&lt;Error&gt; errorMessages;     webservice String  errorMessages;//for testing   } global class BI_VA_Error {      webservice String type;     webservice String message;    }}   And test class is,  @isTest public class BI_VA_AutomationWrapperTestClass  { public static testMethod void unitTest(){      BI_VA_AutomationWrapper.BI_VA_AutomationRequest wrap= new BI_VA_AutomationWrapper.BI_VA_AutomationRequest();        wrap.userName='Test@test.com';     wrap.emailId='Test@test11.com';     wrap.buinessUnit='AH';     wrap.orgName='ORD';     wrap.country='US';     wrap.environment='QA';     wrap.myShopNumber='123456789';     wrap.BidsId='123';     wrap.Type='ResetPassword';              BI_VA_AutomationWrapper.BI_VA_AutomationResponse res= new BI_VA_AutomationWrapper.BI_VA_AutomationResponse();     res.responseStatus = 'Success';     res.myShopNumber = '987654321';     res.errorMessages = 'Test error';      BI_VA_AutomationWrapper.BI_VA_Error error = new BI_VA_AutomationWrapper.BI_VA_Error();     error.type = 'Test';     error.message = 'Test';  }}   Code coverage is 0% only.
70096
I wonder how can I write a catch'em all exception handler in the application level which will give the user the option to resume the application flow?
22784
What is the best way to unit test a method that calls into multiple methods, for example:  modify(string value) {     if(value.Length &gt; 5)  replaceit(value);      else changeit(value); }   This pseudo code has a modify method that (currently) calls either replaceit() or changeit(). I have already wrote tests for replaceit and changeit, so writing a new test for modify will be 99% the same set of code.  I need to test it thought because it may change in the future.    So do I copy paste the existing test code?  Move the test code to a common function?  Any other ideas?  I'm not sure of the best practice here.
30947
I have a trigger on the Custom Object that calls a class. That class makes an HTTP GET request to a Web Service.  However I get the following error:  Callout from triggers are currently not supported.  How can I get data to an external Web Service using Apex code?  However i can use @future method but it can only be support void and this method cannot return results, i need to be able to send data to external ervice and receive acknowlegements from it.
16290
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, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I am building a trigger, a unit test, or other Apex code. I'm working with sObject records, and trying to access related record information. For example, I might have a structure like this: Account a = new Account(Name = 'Test'); insert a;  Opportunity o = new Opportunity(Name = 'Donation', AccountId = a.Id); insert o;  System.assertEquals(o.Account.Name, 'Test', 'Correct Account associated'); // Assertion fails!  Or, in a trigger, I might be aiming for something like this: trigger ContactTrigger on Contact (after insert) {     for (Contact c : Trigger.new) {         if (c.Account.Name == 'Test') {             // Take some action here         }      } }  Why doesn't this work? Why am I getting null values, or NullPointerExceptions?