{"id":326884,"date":"2023-09-09T18:37:18","date_gmt":"2023-09-09T18:37:18","guid":{"rendered":"https:\/\/www.baeldung.com\/?p=165449"},"modified":"2023-09-09T18:37:18","modified_gmt":"2023-09-09T18:37:18","slug":"mock-same-method-with-different-parameters","status":"publish","type":"post","link":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/2023\/09\/09\/mock-same-method-with-different-parameters\/","title":{"rendered":"Mock Same Method with Different Parameters"},"content":{"rendered":"<p class=\"syndicated-attribution\"><meta name= \\\"keywords \\\" content= \\\"\u96fb\u5b50\u8a08\u7b97\u6a5f, \u6559\u80b2, IT \u96fb\u8166\u73ed,\u96fb\u8166\u88dc\u7fd2\uff0c \u96fb\u8166\u73ed\uff0c \u5bb6\u6559\uff0c \u79c1\u4eba\u8001\u5e2b\uff0c \u8cc7\u8a0a\u6280\u8853\uff0c \u7a0b\u5e8f\u8a2d\u8a08\uff0c \u96fb\u5b50\u8a08\u7b97\u6a5f\uff0c \u904a\u6232\uff0c \u860b\u679c\uff0c \u96fb\u5f71\uff0c \u8a08\u7b97\u6a5f\uff0c\u7de8\u78bc\uff0c Java\uff0c C\/C++\uff0c JavaScript\uff0c PHP\uff0c HTML\uff0c CSS\uff0c MySQL\uff0c mobile\uff0c Android\uff0c \u52d5\u6f2b\uff0c Python\uff0c teacher\uff0c \u88dc\u7fd2\uff0c \u96fb\u8166\u88dc\u7fd2 \u8cc7\u8a0a, \u7535\u5b50\u8ba1\u7b97\u673a, IT ,Game, apple, movie, Computer,student,Java,\u6559\u80b2, ,\u5b66\u751f, \u5b66\u4e60, learn, \u6559\u5b66,  Android, apple,anime, animation, \u4fe1\u606f\u6280\u672f, \u7a0b\u5e8f\u8bbe\u8ba1, \u79fb\u52a8\u7535\u8bdd, \u8cc7\u8a0a\u79d1\u6280,Game, Jeu, Juego,Call Of Duty ,\u4f7f\u547d\u53ec\u559a , \u6e38\u620f, \u7535\u5b50\u6e38\u620f,, \u591a\u4eba\u7535\u5b50\u6e38\u620f, \u7f51\u7edc\u6e38\u620f\uff0conline\uff0conline game, \u624b\u673a\u6e38\u620f, mobile \\\"><\/p>\n<p><img src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-1024x536.png\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"\" decoding=\"async\" loading=\"lazy\" style=\"float: left; margin-right: 5px;\" srcset=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-1024x536.png 1024w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-300x157.png 300w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-768x402.png 768w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-100x52.png 100w, https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured.png 1200w\" sizes=\"(max-width: 580px) 100vw, 580px\" \/><\/p>\n<h2 id=\"bd-overview\" data-id=\"overview\">1. Overview<\/h2>\n<div class=\"bd-anchor\" id=\"overview\"><\/div>\n<p>When <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/mockito-series\">mocking<\/a> a method in Java, it can be useful to receive different responses based on the parameters passed in. In this article, we&#8217;ll look at different ways to achieve that goal depending on the complexity of our requirements.<\/p>\n<h2 id=\"bd-setup\" data-id=\"setup\">2. Setup<\/h2>\n<div class=\"bd-anchor\" id=\"setup\"><\/div>\n<p>First, <strong>let&#8217;s create an example service which we want to mock<\/strong>:<\/p>\n<pre><code class=\"language-java\">class ExampleService {\r\n    int getValue(int arg){\r\n        return 1;\r\n    }\r\n}<\/code><\/pre>\n<p>We&#8217;ve got a very simple service with a single method. The method has a single <em>int<\/em> as an argument and returns an <em>int<\/em>. Note that the argument and the return value have no relation, so by default, it&#8217;ll always return 1.<\/p>\n<h2 id=\"bd-limitations-of-consecutive-stubbing\" data-id=\"limitations-of-consecutive-stubbing\">3. Limitations of Consecutive Stubbing<\/h2>\n<div class=\"bd-anchor\" id=\"limitations-of-consecutive-stubbing\"><\/div>\n<p>Let&#8217;s look at consecutive stubbing and what we can and can&#8217;t do with it.<strong> We can use consecutive stubbing to get different arguments from our mock in order regardless of the input we provide.<\/strong> This obviously lacks control over matching particular inputs to desired outputs but is useful in many cases. To do this we pass the method we want to stub to\u00a0<a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/mockito-behavior\"><em>when()<\/em><\/a>. We then chain a call to <em>thenReturn()<\/em> providing the responses in the order we want them:<\/p>\n<pre><code class=\"language-java\">@Test\r\nvoid givenAMethod_whenUsingConsecutiveStubbing_thenExpectResultsInOrder(){\r\n    when(exampleService.getValue(anyInt())).thenReturn(9, 18, 27);\r\n    assertEquals(9, exampleService.getValue(1));\r\n    assertEquals(18, exampleService.getValue(1));\r\n    assertEquals(27, exampleService.getValue(1));\r\n    assertEquals(27, exampleService.getValue(1));\r\n}<\/code><\/pre>\n<p><strong>We can see from the assertions that despite always passing in 1 as the parameter, we received back the expected values in order<\/strong>. Once all the values have been returned, all future calls will return the final value, as seen in the fourth call in our test.<\/p>\n<h2 id=\"bd-stubbing-calls-for-different-parameters\" data-id=\"stubbing-calls-for-different-parameters\">4. Stubbing Calls for Different Parameters<\/h2>\n<div class=\"bd-anchor\" id=\"stubbing-calls-for-different-parameters\"><\/div>\n<p><strong>We can extend our use of <em>when()<\/em> and <em>thenReturn()<\/em> to return different values for different parameters:\u00a0<\/strong><\/p>\n<pre><code class=\"language-java\">@Test\r\nvoid givenAMethod_whenStubbingForMultipleArguments_thenExpectDifferentResults() {\r\n    when(exampleService.getValue(10)).thenReturn(100);\r\n    when(exampleService.getValue(20)).thenReturn(200);\r\n    when(exampleService.getValue(30)).thenReturn(300);\r\n    assertEquals(100, exampleService.getValue(10));\r\n    assertEquals(200, exampleService.getValue(20));\r\n    assertEquals(300, exampleService.getValue(30));\r\n}<\/code><\/pre>\n<p>The argument for <em>when()<\/em> is the method we want to stub, along with the value we want to specify a response for. By chaining the call to <em>when()<\/em> with\u00a0<em>thenReturn(),<\/em> we&#8217;ve instructed the mock to return the requested value when the correct argument is received. We&#8217;re free to apply as many of these as we want to our mock to handle a range of inputs. We&#8217;ll receive the requested return value every time the expected input value is provided.<\/p>\n<h2 id=\"bd-using-thenanswer\" data-id=\"using-thenanswer\">5. Using <em>thenAnswer()<\/em><\/h2>\n<div class=\"bd-anchor\" id=\"using-thenanswer\"><\/div>\n<p><strong>A more complex option, offering maximum control, is to use\u00a0<a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/mockito-additionalanswers\"><em>thenAnswer()<\/em><\/a>.<\/strong> This allows us to take the arguments, perform any computation on them we want, and then return a value that&#8217;ll be outputted when interacting with the mock:<\/p>\n<pre><code class=\"language-java\">@Test\r\nvoid givenAMethod_whenUsingThenAnswer_thenExpectDifferentResults() {\r\n    when(exampleService.getValue(anyInt())).thenAnswer(invocation -&gt; {\r\n        int argument = (int) invocation.getArguments()[0];\r\n        int result;\r\n        switch (argument) {\r\n        case 25:\r\n            result = 125;\r\n            break;\r\n        case 50:\r\n            result = 150;\r\n            break;\r\n        case 75:\r\n            result = 175;\r\n            break;\r\n        default:\r\n            result = 0;\r\n        }\r\n        return result;\r\n    });\r\n    assertEquals(125, exampleService.getValue(25));\r\n    assertEquals(150, exampleService.getValue(50));\r\n    assertEquals(175, exampleService.getValue(75));\r\n}<\/code><\/pre>\n<p>Above, we&#8217;ve grabbed the arguments using <em>getArguments()<\/em> on the provided invocation object. We&#8217;ve assumed a single <em>int<\/em> argument here, but we could&#8217;ve catered for several different types. We also could&#8217;ve checked that there was at least one argument and the cast to an <em>int<\/em> was successful. To demonstrate the capabilities, we&#8217;ve used a <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/www.baeldung.com\/java-switch\"><em>switch<\/em><\/a> statement to return different values based on the input. At the bottom, we can see from the assertions that our mocked service returns the results of the <em>switch<\/em> statement.<\/p>\n<p>This option allows us to handle an unlimited amount of inputs with a single call to\u00a0<em>when()<\/em>. The sacrifice is the readability and maintainability of the tests.<\/p>\n<h2 id=\"bd-conclusion\" data-id=\"conclusion\">6. Conclusion<\/h2>\n<div class=\"bd-anchor\" id=\"conclusion\"><\/div>\n<p>In this tutorial, we&#8217;ve seen three ways of configuring a mocked method to return different values. We looked at consecutive stubbing and saw that it&#8217;s useful for returning known values in order for any input but is very limited beyond that. Using <em>when()<\/em> combined with <em>thenReturn()<\/em> for each potential input offers a simple solution with improved control.\u00a0 Alternatively, we can use <em>thenAnswer()<\/em> for maximum control over the relationship between the given input and the expected output. All three are useful depending on the requirements under test.<\/p>\n<p>As always, the full code for the examples is available <a href=\"https:\/\/feeds.feedblitz.com\/~\/t\/0\/0\/baeldung\/~https:\/\/github.com\/eugenp\/tutorials\/tree\/master\/testing-modules\/mockito-2\">over on GitHub<\/a>.<\/p>\n<p><Img align=\"left\" border=\"0\" height=\"1\" width=\"1\" alt=\"\" style=\"border:0;float:left;margin:0;padding:0;width:1px!important;height:1px!important;\" hspace=\"0\" src=\"https:\/\/feeds.feedblitz.com\/~\/i\/792876920\/0\/baeldung\"><\/p>\n<div style=\"clear:both;padding-top:0.2em;\"><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/792876920\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/792876920\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2021%2F09%2FJava-8-Featured-1024x536.png\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/792876920\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/792876920\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/792876920\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\" style=\"border:0;margin:0;padding:0;\"><\/a>&#160;<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-mock-same-method-other-parameters#respond\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>&#160;<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-mock-same-method-other-parameters\/feed\"><img decoding=\"async\" height=\"20\" style=\"border:0;margin:0;padding:0;\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>&#160;<\/div>\n\n<p class=\"syndicated-attribution\"><figure class= \\\"wp-block-image alignnone \\\"><img src= \\\"http:\/\/itteacheritfreelance.hk\/test\/wordpress\/wp-content\/uploads\/2016\/05\/logo2-2.png\\\" alt=\\\"IT\u96fb\u8166\u88dc\u7fd2 java\u88dc\u7fd2 \u70ba\u5927\u5bb6\u914d\u5c0d\u96fb\u8166\u88dc\u7fd2,IT freelance, \u79c1\u4eba\u8001\u5e2b, PHP\u88dc\u7fd2,CSS\u88dc\u7fd2,XML,Java\u88dc\u7fd2,MySQL\u88dc\u7fd2,graphic design\u88dc\u7fd2,\u4e2d\u5c0f\u5b78ICT\u88dc\u7fd2,\u4e00\u5c0d\u4e00\u79c1\u4eba\u88dc\u7fd2\u548cFreelance\u81ea\u7531\u5de5\u4f5c\u914d\u5c0d\u3002\\\"\/><figcaption>\u7acb\u523b\u8a3b\u518a\u53ca\u5831\u540d\u96fb\u8166\u88dc\u7fd2\u8ab2\u7a0b\u5427!<\/figcaption><\/figure>\r\n<\/br>Find A Teacher Form:\r\n<\/br>https:\/\/docs.google.com\/forms\/d\/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ\/viewform?edit_requested=true#responses\r\n<\/br><\/br>Email:\r\n<\/br>public1989two@gmail.com<br><br><br><br><br><br><br>\r\n<a href=www.itsec.hk style=color:#FFFFFF;>www.itsec.hk<\/a><br>\r\n<a href=\\\"www.itsec.vip\\\" style=color:#FFFFFF;>www.itsec.vip<\/a><br>\r\n<a href=\\\"www.itseceu.uk\\\" style=color:#FFFFFF;>www.itseceu.uk<\/a><br><\/p>","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p><img decoding=\"async\" src=\"https:\/\/www.baeldung.com\/wp-content\/uploads\/2021\/09\/Java-8-Featured-1024x536.png\" class=\"webfeedsFeaturedVisual wp-post-image\" alt=\"\" loading=\"lazy\"><\/p>\n<p>Learn how to mock a method in Java to receive different responses based on the parameters passed in.<\/p>\n<div><a title=\"Like on Facebook\" href=\"https:\/\/feeds.feedblitz.com\/_\/28\/792876920\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/fblike20.png\"><\/a>\u00a0<a title=\"Pin it!\" href=\"https:\/\/feeds.feedblitz.com\/_\/29\/792876920\/baeldung,https%3A%2F%2Fwww.baeldung.com%2Fwp-content%2Fuploads%2F2021%2F09%2FJava-8-Featured-1024x536.png\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/pinterest20.png\"><\/a>\u00a0<a title=\"Tweet This\" href=\"https:\/\/feeds.feedblitz.com\/_\/24\/792876920\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/twitter20.png\"><\/a>\u00a0<a title=\"Subscribe by email\" href=\"https:\/\/feeds.feedblitz.com\/_\/19\/792876920\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/email20.png\"><\/a>\u00a0<a title=\"Subscribe by RSS\" href=\"https:\/\/feeds.feedblitz.com\/_\/20\/792876920\/baeldung\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/rss20.png\"><\/a>\u00a0<a rel=\"NOFOLLOW\" title=\"View Comments\" href=\"https:\/\/www.baeldung.com\/java-mock-same-method-other-parameters#respond\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/comments20.png\"><\/a>\u00a0<a title=\"Follow Comments via RSS\" href=\"https:\/\/www.baeldung.com\/java-mock-same-method-other-parameters\/feed\"><img decoding=\"async\" height=\"20\" src=\"https:\/\/assets.feedblitz.com\/i\/commentsrss20.png\"><\/a>\u00a0<\/div>\n<\/div>","protected":false},"author":1977,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"slim_seo":{"title":"Mock Same Method with Different Parameters - ITTeacherITFreelance.hk","description":"Learn how to mock a method in Java to receive different responses based on the parameters passed in. \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0"},"footnotes":""},"categories":[6,1307],"tags":[],"_links":{"self":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/326884"}],"collection":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/users\/1977"}],"replies":[{"embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/comments?post=326884"}],"version-history":[{"count":1,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/326884\/revisions"}],"predecessor-version":[{"id":326885,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/posts\/326884\/revisions\/326885"}],"wp:attachment":[{"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/media?parent=326884"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/categories?post=326884"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/itteacheritfreelance.hk\/wordpress\/index.php\/wp-json\/wp\/v2\/tags?post=326884"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}