Mockito spy throws stubbing exception2019 Community Moderator ElectionHow to make mock to void methods with mockitoMockito - 0 Matchers Expected, 1 Recorded (InvalidUseOfMatchersException)Wierd mockito InvalidUseOfMatchersException when calling mock from some methodMockito test a void method throws an exceptionMisplaced argument matcher detected here. You cannot use argument matchers outside of verification or stubbing in MockitoReceiving InvalidUseOfMatchersException when stubbing method“Invalid use of argument matchers” but I use matchers onlyMockito doAnswer throws InvalidUseOfMatchersException for unknown reasonMocking a DateFormat class in junit testHow to mock dynamodbmapper scan

The (Easy) Road to Code

Difference between `nmap local-IP-address` and `nmap localhost`

If sound is a longitudinal wave, why can we hear it if our ears aren't aligned with the propagation direction?

ESPP--any reason not to go all in?

What is Tony Stark injecting into himself in Iron Man 3?

How do spaceships determine each other's mass in space?

What can I do if someone tampers with my SSH public key?

Too soon for a plot twist?

What do you call someone who likes to pick fights?

Why is there an extra space when I type "ls" on the Desktop?

What does the Digital Threat scope actually do?

Are these two graphs isomorphic? Why/Why not?

Leveling the sagging side of the home

How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?

How should I solve this integral with changing parameters?

Professor forcing me to attend a conference, I can't afford even with 50% funding

Can I take the the bonus-action attack from Two-Weapon Fighting without taking the Attack action?

Numerical value of Determinant far from what it is supposed to be

Is it a Cyclops number? "Nobody" knows!

Cycles on the torus

How is it possible to drive VGA displays at such high pixel clock frequencies?

What will happen if my luggage gets delayed?

Is there a math expression equivalent to the conditional ternary operator?

Is there a way to make cleveref distinguish two environments with the same counter?



Mockito spy throws stubbing exception



2019 Community Moderator ElectionHow to make mock to void methods with mockitoMockito - 0 Matchers Expected, 1 Recorded (InvalidUseOfMatchersException)Wierd mockito InvalidUseOfMatchersException when calling mock from some methodMockito test a void method throws an exceptionMisplaced argument matcher detected here. You cannot use argument matchers outside of verification or stubbing in MockitoReceiving InvalidUseOfMatchersException when stubbing method“Invalid use of argument matchers” but I use matchers onlyMockito doAnswer throws InvalidUseOfMatchersException for unknown reasonMocking a DateFormat class in junit testHow to mock dynamodbmapper scan










0















I'm trying to spy restTemplate and I wanna to stub 'exchange' method



Here is some code:



spying class



@Bean
fun mockedRestTemplate(): RestTemplate = Mockito.spy(RestTemplate::class.java)


another class



 val headers = HttpHeaders()
headers.setBasicAuth(UUID.randomUUID().toString(), UUID.randomUUID().toString())

val responseBody = "some error message"

val ex = HttpClientErrorException.create(
HttpStatus.NOT_FOUND,
"random",
headers,
responseBody.toByteArray(),
Charset.defaultCharset()
)

val httpEntity = HttpEntity(Any(), headers)

Mockito.doThrow(ex).`when`(restTemplate).exchange(
any() ?: config.randomEndpoint,
any(HttpMethod::class.java) ?: HttpMethod.POST,
any() ?: httpEntity,
any() ?: Foo::class.java
)


What might I be doing wrong here? I get this error message:



 org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at test.suites.controller.FooTest.canGetFailedErrorFieldsIfApiRejectsRequest(FooTest.kt:468)

This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));


When I'm mocking/spying another classes, it works fine










share|improve this question


























    0















    I'm trying to spy restTemplate and I wanna to stub 'exchange' method



    Here is some code:



    spying class



    @Bean
    fun mockedRestTemplate(): RestTemplate = Mockito.spy(RestTemplate::class.java)


    another class



     val headers = HttpHeaders()
    headers.setBasicAuth(UUID.randomUUID().toString(), UUID.randomUUID().toString())

    val responseBody = "some error message"

    val ex = HttpClientErrorException.create(
    HttpStatus.NOT_FOUND,
    "random",
    headers,
    responseBody.toByteArray(),
    Charset.defaultCharset()
    )

    val httpEntity = HttpEntity(Any(), headers)

    Mockito.doThrow(ex).`when`(restTemplate).exchange(
    any() ?: config.randomEndpoint,
    any(HttpMethod::class.java) ?: HttpMethod.POST,
    any() ?: httpEntity,
    any() ?: Foo::class.java
    )


    What might I be doing wrong here? I get this error message:



     org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
    Invalid use of argument matchers!
    0 matchers expected, 1 recorded:
    -> at test.suites.controller.FooTest.canGetFailedErrorFieldsIfApiRejectsRequest(FooTest.kt:468)

    This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
    When using matchers, all arguments have to be provided by matchers.
    For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));


    When I'm mocking/spying another classes, it works fine










    share|improve this question
























      0












      0








      0








      I'm trying to spy restTemplate and I wanna to stub 'exchange' method



      Here is some code:



      spying class



      @Bean
      fun mockedRestTemplate(): RestTemplate = Mockito.spy(RestTemplate::class.java)


      another class



       val headers = HttpHeaders()
      headers.setBasicAuth(UUID.randomUUID().toString(), UUID.randomUUID().toString())

      val responseBody = "some error message"

      val ex = HttpClientErrorException.create(
      HttpStatus.NOT_FOUND,
      "random",
      headers,
      responseBody.toByteArray(),
      Charset.defaultCharset()
      )

      val httpEntity = HttpEntity(Any(), headers)

      Mockito.doThrow(ex).`when`(restTemplate).exchange(
      any() ?: config.randomEndpoint,
      any(HttpMethod::class.java) ?: HttpMethod.POST,
      any() ?: httpEntity,
      any() ?: Foo::class.java
      )


      What might I be doing wrong here? I get this error message:



       org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
      Invalid use of argument matchers!
      0 matchers expected, 1 recorded:
      -> at test.suites.controller.FooTest.canGetFailedErrorFieldsIfApiRejectsRequest(FooTest.kt:468)

      This exception may occur if matchers are combined with raw values:
      //incorrect:
      someMethod(anyObject(), "raw String");
      When using matchers, all arguments have to be provided by matchers.
      For example:
      //correct:
      someMethod(anyObject(), eq("String by matcher"));


      When I'm mocking/spying another classes, it works fine










      share|improve this question














      I'm trying to spy restTemplate and I wanna to stub 'exchange' method



      Here is some code:



      spying class



      @Bean
      fun mockedRestTemplate(): RestTemplate = Mockito.spy(RestTemplate::class.java)


      another class



       val headers = HttpHeaders()
      headers.setBasicAuth(UUID.randomUUID().toString(), UUID.randomUUID().toString())

      val responseBody = "some error message"

      val ex = HttpClientErrorException.create(
      HttpStatus.NOT_FOUND,
      "random",
      headers,
      responseBody.toByteArray(),
      Charset.defaultCharset()
      )

      val httpEntity = HttpEntity(Any(), headers)

      Mockito.doThrow(ex).`when`(restTemplate).exchange(
      any() ?: config.randomEndpoint,
      any(HttpMethod::class.java) ?: HttpMethod.POST,
      any() ?: httpEntity,
      any() ?: Foo::class.java
      )


      What might I be doing wrong here? I get this error message:



       org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
      Invalid use of argument matchers!
      0 matchers expected, 1 recorded:
      -> at test.suites.controller.FooTest.canGetFailedErrorFieldsIfApiRejectsRequest(FooTest.kt:468)

      This exception may occur if matchers are combined with raw values:
      //incorrect:
      someMethod(anyObject(), "raw String");
      When using matchers, all arguments have to be provided by matchers.
      For example:
      //correct:
      someMethod(anyObject(), eq("String by matcher"));


      When I'm mocking/spying another classes, it works fine







      spring spring-boot kotlin mockito






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 6 at 13:52









      user1726616user1726616

      813




      813






















          2 Answers
          2






          active

          oldest

          votes


















          1














          Matchers, such as any(), must be used only in verify() calls. You have:



          val httpEntity = HttpEntity(Any(), headers)


          You can't use any() in this context as you are constructing an object, not verifying a method call. You need to pass in an actual value here.



          Side note: spy() is intended to wrap a real instance. If you're just mocking out an interface (RestTemplate) you should likely be using mock(RestTemplate::class.java) instead.






          share|improve this answer























          • Yes, I know, but this is not fixing the issue. I wanted to wrap real instance, so I could mock only some certain methods.

            – user1726616
            2 days ago


















          0














          I found the problem, but I still didn't get the reason. The issue was in config.randomEndpoint. When I changed the value to string type without injecting config class, the error disappeared.






          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%2f55024742%2fmockito-spy-throws-stubbing-exception%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









            1














            Matchers, such as any(), must be used only in verify() calls. You have:



            val httpEntity = HttpEntity(Any(), headers)


            You can't use any() in this context as you are constructing an object, not verifying a method call. You need to pass in an actual value here.



            Side note: spy() is intended to wrap a real instance. If you're just mocking out an interface (RestTemplate) you should likely be using mock(RestTemplate::class.java) instead.






            share|improve this answer























            • Yes, I know, but this is not fixing the issue. I wanted to wrap real instance, so I could mock only some certain methods.

              – user1726616
              2 days ago















            1














            Matchers, such as any(), must be used only in verify() calls. You have:



            val httpEntity = HttpEntity(Any(), headers)


            You can't use any() in this context as you are constructing an object, not verifying a method call. You need to pass in an actual value here.



            Side note: spy() is intended to wrap a real instance. If you're just mocking out an interface (RestTemplate) you should likely be using mock(RestTemplate::class.java) instead.






            share|improve this answer























            • Yes, I know, but this is not fixing the issue. I wanted to wrap real instance, so I could mock only some certain methods.

              – user1726616
              2 days ago













            1












            1








            1







            Matchers, such as any(), must be used only in verify() calls. You have:



            val httpEntity = HttpEntity(Any(), headers)


            You can't use any() in this context as you are constructing an object, not verifying a method call. You need to pass in an actual value here.



            Side note: spy() is intended to wrap a real instance. If you're just mocking out an interface (RestTemplate) you should likely be using mock(RestTemplate::class.java) instead.






            share|improve this answer













            Matchers, such as any(), must be used only in verify() calls. You have:



            val httpEntity = HttpEntity(Any(), headers)


            You can't use any() in this context as you are constructing an object, not verifying a method call. You need to pass in an actual value here.



            Side note: spy() is intended to wrap a real instance. If you're just mocking out an interface (RestTemplate) you should likely be using mock(RestTemplate::class.java) instead.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 6 at 14:54









            kcoppockkcoppock

            113k39225243




            113k39225243












            • Yes, I know, but this is not fixing the issue. I wanted to wrap real instance, so I could mock only some certain methods.

              – user1726616
              2 days ago

















            • Yes, I know, but this is not fixing the issue. I wanted to wrap real instance, so I could mock only some certain methods.

              – user1726616
              2 days ago
















            Yes, I know, but this is not fixing the issue. I wanted to wrap real instance, so I could mock only some certain methods.

            – user1726616
            2 days ago





            Yes, I know, but this is not fixing the issue. I wanted to wrap real instance, so I could mock only some certain methods.

            – user1726616
            2 days ago













            0














            I found the problem, but I still didn't get the reason. The issue was in config.randomEndpoint. When I changed the value to string type without injecting config class, the error disappeared.






            share|improve this answer



























              0














              I found the problem, but I still didn't get the reason. The issue was in config.randomEndpoint. When I changed the value to string type without injecting config class, the error disappeared.






              share|improve this answer

























                0












                0








                0







                I found the problem, but I still didn't get the reason. The issue was in config.randomEndpoint. When I changed the value to string type without injecting config class, the error disappeared.






                share|improve this answer













                I found the problem, but I still didn't get the reason. The issue was in config.randomEndpoint. When I changed the value to string type without injecting config class, the error disappeared.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 2 days ago









                user1726616user1726616

                813




                813



























                    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%2f55024742%2fmockito-spy-throws-stubbing-exception%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

                    Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                    Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                    Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved