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

                              SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                              은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현