How do you clear the ApexPages.getMessages() collection in a test? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Moderator Election Q&A - Questionnaire 2019 Community Moderator Election ResultsHow do you unit test a trigger when you don't know the required fields?Clear Apex:PageMessages without losing viewstateModifying the trigger collection fieldsHow to test page messages in unit test?How to clear the Info message appearing on the Lookup popup windowtest class fails system.assert but manual upload performs as expectedHow to use clear list when the list returns something that is used for other operations?Clear inputs after saveStrange and hard to reproduce redirect for Visualforce pages in LEX back to the loginpage since Summer'18How to clear the filename and value of apex:inputFile

When is phishing education going too far?

Can a zero nonce be safely used with AES-GCM if the key is random and never used again?

What is the electric potential inside a point charge?

How to say that you spent the night with someone, you were only sleeping and nothing else?

Need a suitable toxic chemical for a murder plot in my novel

I'm thinking of a number

Unable to start mainnet node docker container

Statistical model of ligand substitution

How to colour the US map with Yellow, Green, Red and Blue to minimize the number of states with the colour of Green

What would be Julian Assange's expected punishment, on the current English criminal law?

Was credit for the black hole image misattributed?

Is there folklore associating late breastfeeding with low intelligence and/or gullibility?

Cold is to Refrigerator as warm is to?

How should I respond to a player wanting to catch a sword between their hands?

Why is "Captain Marvel" translated as male in Portugal?

3 doors, three guards, one stone

Stop battery usage [Ubuntu 18]

Active filter with series inductor and resistor - do these exist?

Why use gamma over alpha radiation?

Why don't the Weasley twins use magic outside of school if the Trace can only find the location of spells cast?

What LEGO pieces have "real-world" functionality?

What did Darwin mean by 'squib' here?

The following signatures were invalid: EXPKEYSIG 1397BC53640DB551

Problem when applying foreach loop



How do you clear the ApexPages.getMessages() collection in a test?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
2019 Moderator Election Q&A - Questionnaire
2019 Community Moderator Election ResultsHow do you unit test a trigger when you don't know the required fields?Clear Apex:PageMessages without losing viewstateModifying the trigger collection fieldsHow to test page messages in unit test?How to clear the Info message appearing on the Lookup popup windowtest class fails system.assert but manual upload performs as expectedHow to use clear list when the list returns something that is used for other operations?Clear inputs after saveStrange and hard to reproduce redirect for Visualforce pages in LEX back to the loginpage since Summer'18How to clear the filename and value of apex:inputFile



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








5















The longtime frustration of not being able to clear the messages in tests is marked as a delivered idea in Summer '18 here Add support for clearing PageMessages via Apex.



A failing of that forum is that there never seems to be a link to what was actually done, leaving you back in Google land trying to figure out what that was. In this case I haven't found any new methods in the documentation, and can confirm that the second assert here fails using API 45:



 System.assert(ApexPages.getMessages().size() > 0);
ApexPages.getMessages().clear();
System.assert(ApexPages.getMessages().size() == 0);


So how are the messages cleared?










share|improve this question




























    5















    The longtime frustration of not being able to clear the messages in tests is marked as a delivered idea in Summer '18 here Add support for clearing PageMessages via Apex.



    A failing of that forum is that there never seems to be a link to what was actually done, leaving you back in Google land trying to figure out what that was. In this case I haven't found any new methods in the documentation, and can confirm that the second assert here fails using API 45:



     System.assert(ApexPages.getMessages().size() > 0);
    ApexPages.getMessages().clear();
    System.assert(ApexPages.getMessages().size() == 0);


    So how are the messages cleared?










    share|improve this question
























      5












      5








      5








      The longtime frustration of not being able to clear the messages in tests is marked as a delivered idea in Summer '18 here Add support for clearing PageMessages via Apex.



      A failing of that forum is that there never seems to be a link to what was actually done, leaving you back in Google land trying to figure out what that was. In this case I haven't found any new methods in the documentation, and can confirm that the second assert here fails using API 45:



       System.assert(ApexPages.getMessages().size() > 0);
      ApexPages.getMessages().clear();
      System.assert(ApexPages.getMessages().size() == 0);


      So how are the messages cleared?










      share|improve this question














      The longtime frustration of not being able to clear the messages in tests is marked as a delivered idea in Summer '18 here Add support for clearing PageMessages via Apex.



      A failing of that forum is that there never seems to be a link to what was actually done, leaving you back in Google land trying to figure out what that was. In this case I haven't found any new methods in the documentation, and can confirm that the second assert here fails using API 45:



       System.assert(ApexPages.getMessages().size() > 0);
      ApexPages.getMessages().clear();
      System.assert(ApexPages.getMessages().size() == 0);


      So how are the messages cleared?







      apex visualforce pagemessages






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 3 hours ago









      Keith CKeith C

      96.8k1097216




      96.8k1097216




















          2 Answers
          2






          active

          oldest

          votes


















          5














          It was easy enough to find the Release Note for this feature by looking at Development > Apex.




          Clear Messages on Visualforce Pages While Testing



          Use the new System.Test.clearApexPageMessages() method to clear the messages on a Visualforce page while executing Apex test methods.



          Where: This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.



          Why: You can use the System.Test.clearApexPageMessages() method to test the success or failure of each call to controller methods. Using this function along with the ApexPages.hasMessages() and ApexPages.getMessages() methods allows you to test Visualforce controllers more easily.




          This method is also included in the documentation on the Test Class:




          clearApexPageMessages()

          Clear the messages on a Visualforce page while executing Apex test methods.



          Signature

          public static void clearApexPageMessages()



          Return Value

          Type: void



          Usage

          This method may only be used in tests.



          Example



          @isTest
          static void clearMessagesTest()
          Test.setCurrentPage(new PageReference('/'));
          ApexPages.addMessage(
          new ApexPages.Message(ApexPages.Severity.WARNING, 'Sample Warning')
          );
          System.assertEquals(1, ApexPages.getMessages().size());
          Test.clearApexPageMessages();
          System.assertEquals(0, ApexPages.getMessages().size());







          share|improve this answer























          • Would be easier still if a link was put back in the idea once the feature was documented in the normal product help. Would have saved 15 wasted minutes of my life and 5 of yours.

            – Keith C
            2 hours ago












          • True true. But now anyone who googles it will need only two minutes thanks to the SE network.

            – Adrian Larson
            39 mins ago


















          4














          OK, with a different set of keywords I hit this Clear Messages on Visualforce Pages While Testing release note that talks about the Test.clearApexPageMessages() method. That is explained in the Test Class documentation.



          And happy days, both these assertions pass:



           System.assert(ApexPages.getMessages().size() > 0);
          Test.clearApexPageMessages();
          System.assert(ApexPages.getMessages().size() == 0);





          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%2f257811%2fhow-do-you-clear-the-apexpages-getmessages-collection-in-a-test%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            5














            It was easy enough to find the Release Note for this feature by looking at Development > Apex.




            Clear Messages on Visualforce Pages While Testing



            Use the new System.Test.clearApexPageMessages() method to clear the messages on a Visualforce page while executing Apex test methods.



            Where: This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.



            Why: You can use the System.Test.clearApexPageMessages() method to test the success or failure of each call to controller methods. Using this function along with the ApexPages.hasMessages() and ApexPages.getMessages() methods allows you to test Visualforce controllers more easily.




            This method is also included in the documentation on the Test Class:




            clearApexPageMessages()

            Clear the messages on a Visualforce page while executing Apex test methods.



            Signature

            public static void clearApexPageMessages()



            Return Value

            Type: void



            Usage

            This method may only be used in tests.



            Example



            @isTest
            static void clearMessagesTest()
            Test.setCurrentPage(new PageReference('/'));
            ApexPages.addMessage(
            new ApexPages.Message(ApexPages.Severity.WARNING, 'Sample Warning')
            );
            System.assertEquals(1, ApexPages.getMessages().size());
            Test.clearApexPageMessages();
            System.assertEquals(0, ApexPages.getMessages().size());







            share|improve this answer























            • Would be easier still if a link was put back in the idea once the feature was documented in the normal product help. Would have saved 15 wasted minutes of my life and 5 of yours.

              – Keith C
              2 hours ago












            • True true. But now anyone who googles it will need only two minutes thanks to the SE network.

              – Adrian Larson
              39 mins ago















            5














            It was easy enough to find the Release Note for this feature by looking at Development > Apex.




            Clear Messages on Visualforce Pages While Testing



            Use the new System.Test.clearApexPageMessages() method to clear the messages on a Visualforce page while executing Apex test methods.



            Where: This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.



            Why: You can use the System.Test.clearApexPageMessages() method to test the success or failure of each call to controller methods. Using this function along with the ApexPages.hasMessages() and ApexPages.getMessages() methods allows you to test Visualforce controllers more easily.




            This method is also included in the documentation on the Test Class:




            clearApexPageMessages()

            Clear the messages on a Visualforce page while executing Apex test methods.



            Signature

            public static void clearApexPageMessages()



            Return Value

            Type: void



            Usage

            This method may only be used in tests.



            Example



            @isTest
            static void clearMessagesTest()
            Test.setCurrentPage(new PageReference('/'));
            ApexPages.addMessage(
            new ApexPages.Message(ApexPages.Severity.WARNING, 'Sample Warning')
            );
            System.assertEquals(1, ApexPages.getMessages().size());
            Test.clearApexPageMessages();
            System.assertEquals(0, ApexPages.getMessages().size());







            share|improve this answer























            • Would be easier still if a link was put back in the idea once the feature was documented in the normal product help. Would have saved 15 wasted minutes of my life and 5 of yours.

              – Keith C
              2 hours ago












            • True true. But now anyone who googles it will need only two minutes thanks to the SE network.

              – Adrian Larson
              39 mins ago













            5












            5








            5







            It was easy enough to find the Release Note for this feature by looking at Development > Apex.




            Clear Messages on Visualforce Pages While Testing



            Use the new System.Test.clearApexPageMessages() method to clear the messages on a Visualforce page while executing Apex test methods.



            Where: This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.



            Why: You can use the System.Test.clearApexPageMessages() method to test the success or failure of each call to controller methods. Using this function along with the ApexPages.hasMessages() and ApexPages.getMessages() methods allows you to test Visualforce controllers more easily.




            This method is also included in the documentation on the Test Class:




            clearApexPageMessages()

            Clear the messages on a Visualforce page while executing Apex test methods.



            Signature

            public static void clearApexPageMessages()



            Return Value

            Type: void



            Usage

            This method may only be used in tests.



            Example



            @isTest
            static void clearMessagesTest()
            Test.setCurrentPage(new PageReference('/'));
            ApexPages.addMessage(
            new ApexPages.Message(ApexPages.Severity.WARNING, 'Sample Warning')
            );
            System.assertEquals(1, ApexPages.getMessages().size());
            Test.clearApexPageMessages();
            System.assertEquals(0, ApexPages.getMessages().size());







            share|improve this answer













            It was easy enough to find the Release Note for this feature by looking at Development > Apex.




            Clear Messages on Visualforce Pages While Testing



            Use the new System.Test.clearApexPageMessages() method to clear the messages on a Visualforce page while executing Apex test methods.



            Where: This change applies to Lightning Experience and Salesforce Classic in Enterprise, Performance, Unlimited, and Developer editions.



            Why: You can use the System.Test.clearApexPageMessages() method to test the success or failure of each call to controller methods. Using this function along with the ApexPages.hasMessages() and ApexPages.getMessages() methods allows you to test Visualforce controllers more easily.




            This method is also included in the documentation on the Test Class:




            clearApexPageMessages()

            Clear the messages on a Visualforce page while executing Apex test methods.



            Signature

            public static void clearApexPageMessages()



            Return Value

            Type: void



            Usage

            This method may only be used in tests.



            Example



            @isTest
            static void clearMessagesTest()
            Test.setCurrentPage(new PageReference('/'));
            ApexPages.addMessage(
            new ApexPages.Message(ApexPages.Severity.WARNING, 'Sample Warning')
            );
            System.assertEquals(1, ApexPages.getMessages().size());
            Test.clearApexPageMessages();
            System.assertEquals(0, ApexPages.getMessages().size());








            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 2 hours ago









            Adrian LarsonAdrian Larson

            110k19120256




            110k19120256












            • Would be easier still if a link was put back in the idea once the feature was documented in the normal product help. Would have saved 15 wasted minutes of my life and 5 of yours.

              – Keith C
              2 hours ago












            • True true. But now anyone who googles it will need only two minutes thanks to the SE network.

              – Adrian Larson
              39 mins ago

















            • Would be easier still if a link was put back in the idea once the feature was documented in the normal product help. Would have saved 15 wasted minutes of my life and 5 of yours.

              – Keith C
              2 hours ago












            • True true. But now anyone who googles it will need only two minutes thanks to the SE network.

              – Adrian Larson
              39 mins ago
















            Would be easier still if a link was put back in the idea once the feature was documented in the normal product help. Would have saved 15 wasted minutes of my life and 5 of yours.

            – Keith C
            2 hours ago






            Would be easier still if a link was put back in the idea once the feature was documented in the normal product help. Would have saved 15 wasted minutes of my life and 5 of yours.

            – Keith C
            2 hours ago














            True true. But now anyone who googles it will need only two minutes thanks to the SE network.

            – Adrian Larson
            39 mins ago





            True true. But now anyone who googles it will need only two minutes thanks to the SE network.

            – Adrian Larson
            39 mins ago













            4














            OK, with a different set of keywords I hit this Clear Messages on Visualforce Pages While Testing release note that talks about the Test.clearApexPageMessages() method. That is explained in the Test Class documentation.



            And happy days, both these assertions pass:



             System.assert(ApexPages.getMessages().size() > 0);
            Test.clearApexPageMessages();
            System.assert(ApexPages.getMessages().size() == 0);





            share|improve this answer



























              4














              OK, with a different set of keywords I hit this Clear Messages on Visualforce Pages While Testing release note that talks about the Test.clearApexPageMessages() method. That is explained in the Test Class documentation.



              And happy days, both these assertions pass:



               System.assert(ApexPages.getMessages().size() > 0);
              Test.clearApexPageMessages();
              System.assert(ApexPages.getMessages().size() == 0);





              share|improve this answer

























                4












                4








                4







                OK, with a different set of keywords I hit this Clear Messages on Visualforce Pages While Testing release note that talks about the Test.clearApexPageMessages() method. That is explained in the Test Class documentation.



                And happy days, both these assertions pass:



                 System.assert(ApexPages.getMessages().size() > 0);
                Test.clearApexPageMessages();
                System.assert(ApexPages.getMessages().size() == 0);





                share|improve this answer













                OK, with a different set of keywords I hit this Clear Messages on Visualforce Pages While Testing release note that talks about the Test.clearApexPageMessages() method. That is explained in the Test Class documentation.



                And happy days, both these assertions pass:



                 System.assert(ApexPages.getMessages().size() > 0);
                Test.clearApexPageMessages();
                System.assert(ApexPages.getMessages().size() == 0);






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 2 hours ago









                Keith CKeith C

                96.8k1097216




                96.8k1097216



























                    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.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f257811%2fhow-do-you-clear-the-apexpages-getmessages-collection-in-a-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

                    How to create a command for the “strange m” symbol in latex? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)How do you make your own symbol when Detexify fails?Writing bold small caps with mathpazo packageplus-minus symbol with parenthesis around the minus signGreek character in Beamer document titleHow to create dashed right arrow over symbol?Currency symbol: Turkish LiraDouble prec as a single symbol?Plus Sign Too Big; How to Call adfbullet?Is there a TeX macro for three-legged pi?How do I get my integral-like symbol to align like the integral?How to selectively substitute a letter with another symbol representing the same letterHow do I generate a less than symbol and vertical bar that are the same height?

                    Българска екзархия Съдържание История | Български екзарси | Вижте също | Външни препратки | Литература | Бележки | НавигацияУстав за управлението на българската екзархия. Цариград, 1870Слово на Ловешкия митрополит Иларион при откриването на Българския народен събор в Цариград на 23. II. 1870 г.Българската правда и гръцката кривда. От С. М. (= Софийски Мелетий). Цариград, 1872Предстоятели на Българската екзархияПодмененият ВеликденИнформационна агенция „Фокус“Димитър Ризов. Българите в техните исторически, етнографически и политически граници (Атлас съдържащ 40 карти). Berlin, Königliche Hoflithographie, Hof-Buch- und -Steindruckerei Wilhelm Greve, 1917Report of the International Commission to Inquire into the Causes and Conduct of the Balkan Wars

                    Чепеларе Съдържание География | История | Население | Спортни и природни забележителности | Културни и исторически обекти | Религии | Обществени институции | Известни личности | Редовни събития | Галерия | Източници | Литература | Външни препратки | Навигация41°43′23.99″ с. ш. 24°41′09.99″ и. д. / 41.723333° с. ш. 24.686111° и. д.*ЧепелареЧепеларски Linux fest 2002Начало на Зимен сезон 2005/06Национални хайдушки празници „Капитан Петко Войвода“Град ЧепелареЧепеларе – народният ски курортbgrod.orgwww.terranatura.hit.bgСправка за населението на гр. Исперих, общ. Исперих, обл. РазградМузей на родопския карстМузей на спорта и скитеЧепеларебългарскибългарскианглийскитукИстория на градаСки писти в ЧепелареВремето в ЧепелареРадио и телевизия в ЧепелареЧепеларе мами с родопски чар и добри пистиЕвтин туризъм и снежни атракции в ЧепелареМестоположениеИнформация и снимки от музея на родопския карст3D панорами от ЧепелареЧепелареррр