Issues trying throw checked exception with mockitoHow do you assert that a certain exception is thrown in JUnit 4 tests?How to make mock to void methods with MockitoThrowing exceptions from Mockito mockHow to verify that a specific method was not called using Mockito?Mockito test a void method throws an exceptionHow to mock an exception when creating an instance of a new class using MockitoIs it possible to throw an abstract exception using Mockito?Mockito: inject a class mock into a private interface fieldMockito mock interface returning null in BeforeMockito: replace method that throws an exception

Is it possible to cast two 9th level spells without taking a long rest in 5e?

Did 007 exist before James Bond?

FPGA CPU's, how to find the max speed?

What is the technical explanation of the note "A♭" in a F7 chord in the key of C?

Why do legislative committees exist?

What do mathematicians mean when they say some conjecture can’t be proven using the current technology?

What are some symbols representing peasants/oppressed persons fighting back?

What to look for in climbing shoes?

Capacitor with specific self-resonant frequency?

Why don't commercial aircraft adopt a slightly more seaplane-like design to allow safer ditching in case of emergency?

Advice for paying off student loans and auto loans now that I have my first 'real' job

Credit card stolen every 1-2 years. What am I doing wrong?

If a player tries to persuade somebody, what should that creature roll not to be persuaded?

Can I send medicine to an American visitor in Canada?

Why did Spider-Man take a detour to Dorset?

What systems of robust steganography are out there?

Remove cardinal direction letters

Do First Order blasters maintain a record of when they were fired?

Is this more than a packing puzzle?

Why is "dark" an adverb in this sentence?

Mathematica function equivalent to Matlab's residue function (partial fraction expansion)

What made Windows ME so crash-prone?

Are the errors in this formulation of the simple linear regression model random variables?

Video editor for YouTube



Issues trying throw checked exception with mockito


How do you assert that a certain exception is thrown in JUnit 4 tests?How to make mock to void methods with MockitoThrowing exceptions from Mockito mockHow to verify that a specific method was not called using Mockito?Mockito test a void method throws an exceptionHow to mock an exception when creating an instance of a new class using MockitoIs it possible to throw an abstract exception using Mockito?Mockito: inject a class mock into a private interface fieldMockito mock interface returning null in BeforeMockito: replace method that throws an exception






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








2















I have the below interface



public interface Interface1 
Object Execute(String commandToExecute) throws Exception;



which then I 'm trying to mock so I can test the behaviour of the class that will call it:



Interface1 interfaceMocked = mock(Interface1.class);
when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());
Interface2 objectToTest = new ClassOfInterface2(interfaceMocked);
retrievePrintersMetaData.Retrieve();


But the compiler tells me that there is an unhandled exception.
The definition of the Retrieve method is:



public List<SomeClass> Retrieve() 
try
interface1Object.Execute("");

catch (Exception exception)
return new ArrayList<SomeClass>();




The mockito documentation only shows uses of RuntimeException, and I have not seen anything on similar on StackOverflow.
I'm using Java 1.7u25 and mockito 1.9.5










share|improve this question




























    2















    I have the below interface



    public interface Interface1 
    Object Execute(String commandToExecute) throws Exception;



    which then I 'm trying to mock so I can test the behaviour of the class that will call it:



    Interface1 interfaceMocked = mock(Interface1.class);
    when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());
    Interface2 objectToTest = new ClassOfInterface2(interfaceMocked);
    retrievePrintersMetaData.Retrieve();


    But the compiler tells me that there is an unhandled exception.
    The definition of the Retrieve method is:



    public List<SomeClass> Retrieve() 
    try
    interface1Object.Execute("");

    catch (Exception exception)
    return new ArrayList<SomeClass>();




    The mockito documentation only shows uses of RuntimeException, and I have not seen anything on similar on StackOverflow.
    I'm using Java 1.7u25 and mockito 1.9.5










    share|improve this question
























      2












      2








      2








      I have the below interface



      public interface Interface1 
      Object Execute(String commandToExecute) throws Exception;



      which then I 'm trying to mock so I can test the behaviour of the class that will call it:



      Interface1 interfaceMocked = mock(Interface1.class);
      when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());
      Interface2 objectToTest = new ClassOfInterface2(interfaceMocked);
      retrievePrintersMetaData.Retrieve();


      But the compiler tells me that there is an unhandled exception.
      The definition of the Retrieve method is:



      public List<SomeClass> Retrieve() 
      try
      interface1Object.Execute("");

      catch (Exception exception)
      return new ArrayList<SomeClass>();




      The mockito documentation only shows uses of RuntimeException, and I have not seen anything on similar on StackOverflow.
      I'm using Java 1.7u25 and mockito 1.9.5










      share|improve this question














      I have the below interface



      public interface Interface1 
      Object Execute(String commandToExecute) throws Exception;



      which then I 'm trying to mock so I can test the behaviour of the class that will call it:



      Interface1 interfaceMocked = mock(Interface1.class);
      when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());
      Interface2 objectToTest = new ClassOfInterface2(interfaceMocked);
      retrievePrintersMetaData.Retrieve();


      But the compiler tells me that there is an unhandled exception.
      The definition of the Retrieve method is:



      public List<SomeClass> Retrieve() 
      try
      interface1Object.Execute("");

      catch (Exception exception)
      return new ArrayList<SomeClass>();




      The mockito documentation only shows uses of RuntimeException, and I have not seen anything on similar on StackOverflow.
      I'm using Java 1.7u25 and mockito 1.9.5







      java mockito






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jul 6 '13 at 20:21









      Miyamoto AkiraMiyamoto Akira

      2127 silver badges16 bronze badges




      2127 silver badges16 bronze badges






















          3 Answers
          3






          active

          oldest

          votes


















          3














          Assuming your test method doesn't declare that it throws Exception, the compiler's absolutely right. This line:



          when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());


          ... calls Execute on an instance of Interface1. That can throw Exception, so you either need to catch it or declare that your method throws it.



          I would personally recommend just declaring that the test method throws Exception. Nothing else will care about that declaration, and you really don't want to catch it.






          share|improve this answer























          • Solves the problem. I was expecting Mockito would take care of it. Not yet used to the particulars of checked exceptions.

            – Miyamoto Akira
            Jul 6 '13 at 21:24


















          0














          You shouldn't be having a problem if your method returns something and throws your error. Now if your method returns void you won't be able to throw an error.



          Now the real thing is that you're not testing that your interface throws an exception, instead what you're testing what happens when an exception is thrown within this method.



          public List<SomeClass> Retrieve() 
          try
          interface1Object.Execute("");

          catch (Exception exception)
          return handleException(exception);



          protected List<SomeClass> handleException(Exception exception)
          return new ArrayList<SomeClass>();



          Then you just call your handleException method and make sure it returns the correct thing. If you need to make sure that your interface is throwing an exception, then that is a different test for your interface class.



          It might seem sucky that you are having to make a method for a single line but that's what happens sometimes if you want testable code.






          share|improve this answer






























            0














            You can use doAnswer method of Mockito to thrown checked exceptions, like this



            Mockito.doAnswer(
            invocation ->
            throw new Exception("It's not bad, it's good");
            )
            .when(interfaceMocked)
            .Execute(org.mockito.ArgumentMatchers.anyString());





            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              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: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              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%2fstackoverflow.com%2fquestions%2f17506767%2fissues-trying-throw-checked-exception-with-mockito%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              3














              Assuming your test method doesn't declare that it throws Exception, the compiler's absolutely right. This line:



              when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());


              ... calls Execute on an instance of Interface1. That can throw Exception, so you either need to catch it or declare that your method throws it.



              I would personally recommend just declaring that the test method throws Exception. Nothing else will care about that declaration, and you really don't want to catch it.






              share|improve this answer























              • Solves the problem. I was expecting Mockito would take care of it. Not yet used to the particulars of checked exceptions.

                – Miyamoto Akira
                Jul 6 '13 at 21:24















              3














              Assuming your test method doesn't declare that it throws Exception, the compiler's absolutely right. This line:



              when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());


              ... calls Execute on an instance of Interface1. That can throw Exception, so you either need to catch it or declare that your method throws it.



              I would personally recommend just declaring that the test method throws Exception. Nothing else will care about that declaration, and you really don't want to catch it.






              share|improve this answer























              • Solves the problem. I was expecting Mockito would take care of it. Not yet used to the particulars of checked exceptions.

                – Miyamoto Akira
                Jul 6 '13 at 21:24













              3












              3








              3







              Assuming your test method doesn't declare that it throws Exception, the compiler's absolutely right. This line:



              when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());


              ... calls Execute on an instance of Interface1. That can throw Exception, so you either need to catch it or declare that your method throws it.



              I would personally recommend just declaring that the test method throws Exception. Nothing else will care about that declaration, and you really don't want to catch it.






              share|improve this answer













              Assuming your test method doesn't declare that it throws Exception, the compiler's absolutely right. This line:



              when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());


              ... calls Execute on an instance of Interface1. That can throw Exception, so you either need to catch it or declare that your method throws it.



              I would personally recommend just declaring that the test method throws Exception. Nothing else will care about that declaration, and you really don't want to catch it.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Jul 6 '13 at 20:23









              Jon SkeetJon Skeet

              1118k709 gold badges8142 silver badges8547 bronze badges




              1118k709 gold badges8142 silver badges8547 bronze badges












              • Solves the problem. I was expecting Mockito would take care of it. Not yet used to the particulars of checked exceptions.

                – Miyamoto Akira
                Jul 6 '13 at 21:24

















              • Solves the problem. I was expecting Mockito would take care of it. Not yet used to the particulars of checked exceptions.

                – Miyamoto Akira
                Jul 6 '13 at 21:24
















              Solves the problem. I was expecting Mockito would take care of it. Not yet used to the particulars of checked exceptions.

              – Miyamoto Akira
              Jul 6 '13 at 21:24





              Solves the problem. I was expecting Mockito would take care of it. Not yet used to the particulars of checked exceptions.

              – Miyamoto Akira
              Jul 6 '13 at 21:24













              0














              You shouldn't be having a problem if your method returns something and throws your error. Now if your method returns void you won't be able to throw an error.



              Now the real thing is that you're not testing that your interface throws an exception, instead what you're testing what happens when an exception is thrown within this method.



              public List<SomeClass> Retrieve() 
              try
              interface1Object.Execute("");

              catch (Exception exception)
              return handleException(exception);



              protected List<SomeClass> handleException(Exception exception)
              return new ArrayList<SomeClass>();



              Then you just call your handleException method and make sure it returns the correct thing. If you need to make sure that your interface is throwing an exception, then that is a different test for your interface class.



              It might seem sucky that you are having to make a method for a single line but that's what happens sometimes if you want testable code.






              share|improve this answer



























                0














                You shouldn't be having a problem if your method returns something and throws your error. Now if your method returns void you won't be able to throw an error.



                Now the real thing is that you're not testing that your interface throws an exception, instead what you're testing what happens when an exception is thrown within this method.



                public List<SomeClass> Retrieve() 
                try
                interface1Object.Execute("");

                catch (Exception exception)
                return handleException(exception);



                protected List<SomeClass> handleException(Exception exception)
                return new ArrayList<SomeClass>();



                Then you just call your handleException method and make sure it returns the correct thing. If you need to make sure that your interface is throwing an exception, then that is a different test for your interface class.



                It might seem sucky that you are having to make a method for a single line but that's what happens sometimes if you want testable code.






                share|improve this answer

























                  0












                  0








                  0







                  You shouldn't be having a problem if your method returns something and throws your error. Now if your method returns void you won't be able to throw an error.



                  Now the real thing is that you're not testing that your interface throws an exception, instead what you're testing what happens when an exception is thrown within this method.



                  public List<SomeClass> Retrieve() 
                  try
                  interface1Object.Execute("");

                  catch (Exception exception)
                  return handleException(exception);



                  protected List<SomeClass> handleException(Exception exception)
                  return new ArrayList<SomeClass>();



                  Then you just call your handleException method and make sure it returns the correct thing. If you need to make sure that your interface is throwing an exception, then that is a different test for your interface class.



                  It might seem sucky that you are having to make a method for a single line but that's what happens sometimes if you want testable code.






                  share|improve this answer













                  You shouldn't be having a problem if your method returns something and throws your error. Now if your method returns void you won't be able to throw an error.



                  Now the real thing is that you're not testing that your interface throws an exception, instead what you're testing what happens when an exception is thrown within this method.



                  public List<SomeClass> Retrieve() 
                  try
                  interface1Object.Execute("");

                  catch (Exception exception)
                  return handleException(exception);



                  protected List<SomeClass> handleException(Exception exception)
                  return new ArrayList<SomeClass>();



                  Then you just call your handleException method and make sure it returns the correct thing. If you need to make sure that your interface is throwing an exception, then that is a different test for your interface class.



                  It might seem sucky that you are having to make a method for a single line but that's what happens sometimes if you want testable code.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Dec 4 '14 at 23:41









                  MinceManMinceMan

                  6,08831 silver badges35 bronze badges




                  6,08831 silver badges35 bronze badges





















                      0














                      You can use doAnswer method of Mockito to thrown checked exceptions, like this



                      Mockito.doAnswer(
                      invocation ->
                      throw new Exception("It's not bad, it's good");
                      )
                      .when(interfaceMocked)
                      .Execute(org.mockito.ArgumentMatchers.anyString());





                      share|improve this answer



























                        0














                        You can use doAnswer method of Mockito to thrown checked exceptions, like this



                        Mockito.doAnswer(
                        invocation ->
                        throw new Exception("It's not bad, it's good");
                        )
                        .when(interfaceMocked)
                        .Execute(org.mockito.ArgumentMatchers.anyString());





                        share|improve this answer

























                          0












                          0








                          0







                          You can use doAnswer method of Mockito to thrown checked exceptions, like this



                          Mockito.doAnswer(
                          invocation ->
                          throw new Exception("It's not bad, it's good");
                          )
                          .when(interfaceMocked)
                          .Execute(org.mockito.ArgumentMatchers.anyString());





                          share|improve this answer













                          You can use doAnswer method of Mockito to thrown checked exceptions, like this



                          Mockito.doAnswer(
                          invocation ->
                          throw new Exception("It's not bad, it's good");
                          )
                          .when(interfaceMocked)
                          .Execute(org.mockito.ArgumentMatchers.anyString());






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 26 at 7:32









                          HasasnHasasn

                          5035 silver badges5 bronze badges




                          5035 silver badges5 bronze badges



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • 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%2fstackoverflow.com%2fquestions%2f17506767%2fissues-trying-throw-checked-exception-with-mockito%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

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                              Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript