How do I write an Apex unit test?












5














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 canonical-qa 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.










share|improve this question





























    5














    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 canonical-qa 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.










    share|improve this question



























      5












      5








      5


      3





      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 canonical-qa 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.










      share|improve this question















      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 canonical-qa 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.







      unit-test canonical-qa






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      asked Dec 27 at 16:20


























      community wiki





      David Reed























          1 Answer
          1






          active

          oldest

          votes


















          6














          This answer is not intended to teach you everything about writing unit tests, nor to specifically answer every question, but to provide a quick summary and links to the resources that will help you move forward and develop more specific questions that SFSE can assist with.



          Overview



          Unit (and integration) testing is a big topic, but it starts with a small set of principles. If you've never written a unit test before, we strongly encourage you to complete the Unit Testing on the Lightning Platform Trailhead module and read at least the Month of Testing series. These materials and others are linked under Resources, below.



          Fundamentally, testing comprises three steps, all of which take place within the context of a unit test:




          1. Creating test data as input for your code, which is designed ensure that a specific logical path is executed. This can take the form of values in memory or of creating and inserting sObjects.

          2. Executing that code, meaning that that specific code path runs within a method annotated with the @isTest annotation.

          3. Writing assertions to demonstrate that the results of the code are correct and as expected for the given inputs.


          Then, all code that is executed under step (2) is counted as covered under Salesforce's code coverage metrics. Code coverage is a side effect of high quality unit tests. Salesforce uses code coverage as a proxy to measure the presence of unit tests in your deployments.



          Unit testing principles are quite general, and most Apex code is not special in the sense of requiring unique approaches to create a successful test. Techniques for implementing tests that perform all three steps are taught in the resources we include below.



          Test Isolation



          On Salesforce, all unit tests are executed in an isolated context. In this context, your code cannot see data in your organization, including ordinary records as well as Custom Settings. However, metadata records, including Users and Custom Metadata, are visible. An older annotation, seeAllData=true, allows tests to see all data in the Salesforce org. Use of this annotation is strongly discouraged for new unit tests, and is considered a very bad practice. It's important instead to follow the first step above, by designing test data as input for your code; this insulates your tests against fragility in the org's data.



          Smoke Tests (Tests without Assertions)



          Unit tests that don't contain assertions are often called smoke tests. These tests have very limited value, because they show nothing other than that your code does not crash under a specific set of circumstances. They don't prove the code works or does what it's intended to do.



          Resources



          Trailhead





          • Unit Testing on the Lightning Platform, the newest and most comprehensive module on unit testing offered by Trailhead.

          • Apex Testing


          • Apex REST Callouts and Apex SOAP Callouts cover the use of mocking to test callout code.


          Apex Developer Guide




          • Testing Apex


          Blogs and Articles




          • Month of Testing series from the Salesforce Developers blog.


            • Part 1: Why We Test

            • Part 2: Apex Testing in Depth

            • Part 3: Advanced Topics in Salesforce Unit Testing




          Dreamforce Video Content





          • Get Your Code Coverage to 100% by Patrick Connelly. This talk covers intermediate-level testing topics and best practices.


          Third-Party Testing Frameworks (Advanced Topics)





          • ApexMocks, an open-source mocking framework for Apex.


          • Force-DI, a framework for pervasive dependency injection.






          share|improve this answer























            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "459"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f244788%2fhow-do-i-write-an-apex-unit-test%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            6














            This answer is not intended to teach you everything about writing unit tests, nor to specifically answer every question, but to provide a quick summary and links to the resources that will help you move forward and develop more specific questions that SFSE can assist with.



            Overview



            Unit (and integration) testing is a big topic, but it starts with a small set of principles. If you've never written a unit test before, we strongly encourage you to complete the Unit Testing on the Lightning Platform Trailhead module and read at least the Month of Testing series. These materials and others are linked under Resources, below.



            Fundamentally, testing comprises three steps, all of which take place within the context of a unit test:




            1. Creating test data as input for your code, which is designed ensure that a specific logical path is executed. This can take the form of values in memory or of creating and inserting sObjects.

            2. Executing that code, meaning that that specific code path runs within a method annotated with the @isTest annotation.

            3. Writing assertions to demonstrate that the results of the code are correct and as expected for the given inputs.


            Then, all code that is executed under step (2) is counted as covered under Salesforce's code coverage metrics. Code coverage is a side effect of high quality unit tests. Salesforce uses code coverage as a proxy to measure the presence of unit tests in your deployments.



            Unit testing principles are quite general, and most Apex code is not special in the sense of requiring unique approaches to create a successful test. Techniques for implementing tests that perform all three steps are taught in the resources we include below.



            Test Isolation



            On Salesforce, all unit tests are executed in an isolated context. In this context, your code cannot see data in your organization, including ordinary records as well as Custom Settings. However, metadata records, including Users and Custom Metadata, are visible. An older annotation, seeAllData=true, allows tests to see all data in the Salesforce org. Use of this annotation is strongly discouraged for new unit tests, and is considered a very bad practice. It's important instead to follow the first step above, by designing test data as input for your code; this insulates your tests against fragility in the org's data.



            Smoke Tests (Tests without Assertions)



            Unit tests that don't contain assertions are often called smoke tests. These tests have very limited value, because they show nothing other than that your code does not crash under a specific set of circumstances. They don't prove the code works or does what it's intended to do.



            Resources



            Trailhead





            • Unit Testing on the Lightning Platform, the newest and most comprehensive module on unit testing offered by Trailhead.

            • Apex Testing


            • Apex REST Callouts and Apex SOAP Callouts cover the use of mocking to test callout code.


            Apex Developer Guide




            • Testing Apex


            Blogs and Articles




            • Month of Testing series from the Salesforce Developers blog.


              • Part 1: Why We Test

              • Part 2: Apex Testing in Depth

              • Part 3: Advanced Topics in Salesforce Unit Testing




            Dreamforce Video Content





            • Get Your Code Coverage to 100% by Patrick Connelly. This talk covers intermediate-level testing topics and best practices.


            Third-Party Testing Frameworks (Advanced Topics)





            • ApexMocks, an open-source mocking framework for Apex.


            • Force-DI, a framework for pervasive dependency injection.






            share|improve this answer




























              6














              This answer is not intended to teach you everything about writing unit tests, nor to specifically answer every question, but to provide a quick summary and links to the resources that will help you move forward and develop more specific questions that SFSE can assist with.



              Overview



              Unit (and integration) testing is a big topic, but it starts with a small set of principles. If you've never written a unit test before, we strongly encourage you to complete the Unit Testing on the Lightning Platform Trailhead module and read at least the Month of Testing series. These materials and others are linked under Resources, below.



              Fundamentally, testing comprises three steps, all of which take place within the context of a unit test:




              1. Creating test data as input for your code, which is designed ensure that a specific logical path is executed. This can take the form of values in memory or of creating and inserting sObjects.

              2. Executing that code, meaning that that specific code path runs within a method annotated with the @isTest annotation.

              3. Writing assertions to demonstrate that the results of the code are correct and as expected for the given inputs.


              Then, all code that is executed under step (2) is counted as covered under Salesforce's code coverage metrics. Code coverage is a side effect of high quality unit tests. Salesforce uses code coverage as a proxy to measure the presence of unit tests in your deployments.



              Unit testing principles are quite general, and most Apex code is not special in the sense of requiring unique approaches to create a successful test. Techniques for implementing tests that perform all three steps are taught in the resources we include below.



              Test Isolation



              On Salesforce, all unit tests are executed in an isolated context. In this context, your code cannot see data in your organization, including ordinary records as well as Custom Settings. However, metadata records, including Users and Custom Metadata, are visible. An older annotation, seeAllData=true, allows tests to see all data in the Salesforce org. Use of this annotation is strongly discouraged for new unit tests, and is considered a very bad practice. It's important instead to follow the first step above, by designing test data as input for your code; this insulates your tests against fragility in the org's data.



              Smoke Tests (Tests without Assertions)



              Unit tests that don't contain assertions are often called smoke tests. These tests have very limited value, because they show nothing other than that your code does not crash under a specific set of circumstances. They don't prove the code works or does what it's intended to do.



              Resources



              Trailhead





              • Unit Testing on the Lightning Platform, the newest and most comprehensive module on unit testing offered by Trailhead.

              • Apex Testing


              • Apex REST Callouts and Apex SOAP Callouts cover the use of mocking to test callout code.


              Apex Developer Guide




              • Testing Apex


              Blogs and Articles




              • Month of Testing series from the Salesforce Developers blog.


                • Part 1: Why We Test

                • Part 2: Apex Testing in Depth

                • Part 3: Advanced Topics in Salesforce Unit Testing




              Dreamforce Video Content





              • Get Your Code Coverage to 100% by Patrick Connelly. This talk covers intermediate-level testing topics and best practices.


              Third-Party Testing Frameworks (Advanced Topics)





              • ApexMocks, an open-source mocking framework for Apex.


              • Force-DI, a framework for pervasive dependency injection.






              share|improve this answer


























                6












                6








                6






                This answer is not intended to teach you everything about writing unit tests, nor to specifically answer every question, but to provide a quick summary and links to the resources that will help you move forward and develop more specific questions that SFSE can assist with.



                Overview



                Unit (and integration) testing is a big topic, but it starts with a small set of principles. If you've never written a unit test before, we strongly encourage you to complete the Unit Testing on the Lightning Platform Trailhead module and read at least the Month of Testing series. These materials and others are linked under Resources, below.



                Fundamentally, testing comprises three steps, all of which take place within the context of a unit test:




                1. Creating test data as input for your code, which is designed ensure that a specific logical path is executed. This can take the form of values in memory or of creating and inserting sObjects.

                2. Executing that code, meaning that that specific code path runs within a method annotated with the @isTest annotation.

                3. Writing assertions to demonstrate that the results of the code are correct and as expected for the given inputs.


                Then, all code that is executed under step (2) is counted as covered under Salesforce's code coverage metrics. Code coverage is a side effect of high quality unit tests. Salesforce uses code coverage as a proxy to measure the presence of unit tests in your deployments.



                Unit testing principles are quite general, and most Apex code is not special in the sense of requiring unique approaches to create a successful test. Techniques for implementing tests that perform all three steps are taught in the resources we include below.



                Test Isolation



                On Salesforce, all unit tests are executed in an isolated context. In this context, your code cannot see data in your organization, including ordinary records as well as Custom Settings. However, metadata records, including Users and Custom Metadata, are visible. An older annotation, seeAllData=true, allows tests to see all data in the Salesforce org. Use of this annotation is strongly discouraged for new unit tests, and is considered a very bad practice. It's important instead to follow the first step above, by designing test data as input for your code; this insulates your tests against fragility in the org's data.



                Smoke Tests (Tests without Assertions)



                Unit tests that don't contain assertions are often called smoke tests. These tests have very limited value, because they show nothing other than that your code does not crash under a specific set of circumstances. They don't prove the code works or does what it's intended to do.



                Resources



                Trailhead





                • Unit Testing on the Lightning Platform, the newest and most comprehensive module on unit testing offered by Trailhead.

                • Apex Testing


                • Apex REST Callouts and Apex SOAP Callouts cover the use of mocking to test callout code.


                Apex Developer Guide




                • Testing Apex


                Blogs and Articles




                • Month of Testing series from the Salesforce Developers blog.


                  • Part 1: Why We Test

                  • Part 2: Apex Testing in Depth

                  • Part 3: Advanced Topics in Salesforce Unit Testing




                Dreamforce Video Content





                • Get Your Code Coverage to 100% by Patrick Connelly. This talk covers intermediate-level testing topics and best practices.


                Third-Party Testing Frameworks (Advanced Topics)





                • ApexMocks, an open-source mocking framework for Apex.


                • Force-DI, a framework for pervasive dependency injection.






                share|improve this answer














                This answer is not intended to teach you everything about writing unit tests, nor to specifically answer every question, but to provide a quick summary and links to the resources that will help you move forward and develop more specific questions that SFSE can assist with.



                Overview



                Unit (and integration) testing is a big topic, but it starts with a small set of principles. If you've never written a unit test before, we strongly encourage you to complete the Unit Testing on the Lightning Platform Trailhead module and read at least the Month of Testing series. These materials and others are linked under Resources, below.



                Fundamentally, testing comprises three steps, all of which take place within the context of a unit test:




                1. Creating test data as input for your code, which is designed ensure that a specific logical path is executed. This can take the form of values in memory or of creating and inserting sObjects.

                2. Executing that code, meaning that that specific code path runs within a method annotated with the @isTest annotation.

                3. Writing assertions to demonstrate that the results of the code are correct and as expected for the given inputs.


                Then, all code that is executed under step (2) is counted as covered under Salesforce's code coverage metrics. Code coverage is a side effect of high quality unit tests. Salesforce uses code coverage as a proxy to measure the presence of unit tests in your deployments.



                Unit testing principles are quite general, and most Apex code is not special in the sense of requiring unique approaches to create a successful test. Techniques for implementing tests that perform all three steps are taught in the resources we include below.



                Test Isolation



                On Salesforce, all unit tests are executed in an isolated context. In this context, your code cannot see data in your organization, including ordinary records as well as Custom Settings. However, metadata records, including Users and Custom Metadata, are visible. An older annotation, seeAllData=true, allows tests to see all data in the Salesforce org. Use of this annotation is strongly discouraged for new unit tests, and is considered a very bad practice. It's important instead to follow the first step above, by designing test data as input for your code; this insulates your tests against fragility in the org's data.



                Smoke Tests (Tests without Assertions)



                Unit tests that don't contain assertions are often called smoke tests. These tests have very limited value, because they show nothing other than that your code does not crash under a specific set of circumstances. They don't prove the code works or does what it's intended to do.



                Resources



                Trailhead





                • Unit Testing on the Lightning Platform, the newest and most comprehensive module on unit testing offered by Trailhead.

                • Apex Testing


                • Apex REST Callouts and Apex SOAP Callouts cover the use of mocking to test callout code.


                Apex Developer Guide




                • Testing Apex


                Blogs and Articles




                • Month of Testing series from the Salesforce Developers blog.


                  • Part 1: Why We Test

                  • Part 2: Apex Testing in Depth

                  • Part 3: Advanced Topics in Salesforce Unit Testing




                Dreamforce Video Content





                • Get Your Code Coverage to 100% by Patrick Connelly. This talk covers intermediate-level testing topics and best practices.


                Third-Party Testing Frameworks (Advanced Topics)





                • ApexMocks, an open-source mocking framework for Apex.


                • Force-DI, a framework for pervasive dependency injection.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 27 at 16:53


























                community wiki





                3 revs
                David Reed































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Salesforce Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f244788%2fhow-do-i-write-an-apex-unit-test%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Human spaceflight

                    Can not write log (Is /dev/pts mounted?) - openpty in Ubuntu-on-Windows?

                    張江高科駅