{"id":12274,"date":"2012-08-20T09:14:00","date_gmt":"2012-08-20T08:14:00","guid":{"rendered":"https:\/\/touk.pl\/blog\/?guid=bf4013176cdf0e1f539b82e96556308f"},"modified":"2022-07-27T08:54:07","modified_gmt":"2022-07-27T06:54:07","slug":"how-to-use-mocks-in-controller-tests","status":"publish","type":"post","link":"https:\/\/touk.pl\/blog\/2012\/08\/20\/how-to-use-mocks-in-controller-tests\/","title":{"rendered":"How to use mocks in controller tests"},"content":{"rendered":"<p>Even since I started to write tests for my Grails application I couldn\u2019t find many articles on using mocks. Everyone is talking about tests and TDD but if you search for it there isn\u2019t many articles.<\/p>\n<p>Today I want to share with you a test with mocks for a simple and complete scenario. I have a simple application that can fetch Twitter tweets and present it to user. I use REST service and I use GET to fetch tweets by id like this: <a href=\"http:\/\/api.twitter.com\/1\/statuses\/show\/236024636775735296.json\">http:\/\/api.twitter.com\/1\/statuses\/show\/236024636775735296.json<\/a>. You can copy and paste it into your browser to see a result.<\/p>\n<p>My application uses Grails 2.1 with spock-0.6 for tests. I have <code>TwitterReaderService<\/code> that fetches tweets by id, then I parse a response into my <code>Tweet<\/code> class.<\/p>\n<pre class=\"prettyprint\"><br \/>class TwitterReaderService {<br \/>    Tweet readTweet(String id) throws TwitterError {<br \/>        try {<br \/>            String jsonBody = callTwitter(id)<br \/>            Tweet parsedTweet = parseBody(jsonBody)<br \/>            return parsedTweet<br \/>        } catch (Throwable t) {<br \/>            throw new TwitterError(t)<br \/>        }<br \/>    }<br \/><br \/>    private String callTwitter(String id) {<br \/>        \/\/ TODO: implementation<br \/>    }<br \/><br \/>    private Tweet parseBody(String jsonBody) {<br \/>        \/\/ TODO: implementation<br \/>    }<br \/>}<br \/><br \/>class Tweet {<br \/>    String id<br \/>    String userId<br \/>    String username<br \/>    String text<br \/>    Date createdAt<br \/>}<br \/><br \/>class TwitterError extends RuntimeException {}<br \/><\/pre>\n<p><code>TwitterController<\/code> plays main part here. Users call <code>show<\/code> action along with <code>id<\/code> of a tweet. This action is my subject under test. I\u2019ve implemented some basic functionality. It\u2019s easier to focus on it while writing tests.<\/p>\n<pre class=\"prettyprint\"><br \/>class TwitterController {<br \/>    def twitterReaderService<br \/><br \/>    def index() {<br \/>    }<br \/><br \/>    def show() {<br \/>        Tweet tweet = twitterReaderService.readTweet(params.id)<br \/>        if (tweet == null) {<br \/>            flash.message = 'Tweet not found'<br \/>            redirect(action: 'index')<br \/>            return<br \/>        }<br \/><br \/>        [tweet: tweet]    }<br \/>}<br \/><\/pre>\n<p>Let\u2019s start writing a test from scratch. Most important thing here is that I use mock for my <code>TwitterReaderService<\/code>. I do not construct <code>new TwitterReaderService()<\/code>, because in this test I test only <code>TwitterController<\/code>. I am not interested in injected service. I know how this service is supposed to work and I am not interested in internals. So before every test I inject a <code>twitterReaderServiceMock<\/code> into controller:<\/p>\n<pre class=\"prettyprint\"><br \/>import grails.test.mixin.TestFor<br \/>import spock.lang.Specification<br \/><br \/>@TestFor(TwitterController)<br \/>class TwitterControllerSpec extends Specification {<br \/>    TwitterReaderService twitterReaderServiceMock = Mock(TwitterReaderService)<br \/><br \/>    def setup() {<br \/>        controller.twitterReaderService = twitterReaderServiceMock<br \/>    }<br \/>}<br \/><\/pre>\n<p>Now it\u2019s time to think what scenarios I need to test. This line from <code>TwitterReaderService<\/code> is the most important:<\/p>\n<pre class=\"prettyprint\"><br \/>Tweet readTweet(String id) throws TwitterError<br \/><\/pre>\n<p>You must think of this method like a black box right now. You know nothing of internals from controller\u2019s point of view. You\u2019re only interested what can be returned for you:<\/p>\n<ul>\n<li>a <code>TwitterError<\/code> can be thrown<\/li>\n<li><code>null<\/code> can be returned<\/li>\n<li><code>Tweet<\/code> instance can be returned<\/li>\n<\/ul>\n<p>This list is your test blueprint. Now answer a simple question for each element: \u201cWhat do I want my controller to do in this situation?\u201d and you have plan test:<\/p>\n<ul>\n<li><code>show<\/code> action should redirect to index if <code>TwitterError<\/code> is thrown and inform about error<\/li>\n<li><code>show<\/code> action should redirect to index and inform if tweet is not found<\/li>\n<li><code>show<\/code> action should show found tweet<\/li>\n<\/ul>\n<p>That was easy and straightforward! And now is the best part: we use <code>twitterReaderServiceMock<\/code> to mock each of these three scenarios!<\/p>\n<p>In Spock there is a good documentation about <a href=\"http:\/\/code.google.com\/p\/spock\/wiki\/Interactions\"> interaction with mocks<\/a>. You declare what methods are called, how many times, what parameters are given and what should be returned. Remember a black box? Mock is your black box with detailed instruction, e.g.: <em>I expect you that if receive exactly one call to <code>readTweet<\/code> with parameter \u20181\u2019 then you should throw me a <code>TwitterError<\/code><\/em>. Rephrase this sentence out loud and look at this:<\/p>\n<pre class=\"prettyprint\"><br \/>1 * twitterReaderServiceMock.readTweet('1') >> { throw new TwitterError() }<br \/><\/pre>\n<p>This is a valid interaction definition on mock! It\u2019s that easy! Here is a complete test that fails for now:<\/p>\n<pre class=\"prettyprint\"><br \/>import grails.test.mixin.TestFor<br \/>import spock.lang.Specification<br \/><br \/>@TestFor(TwitterController)<br \/>class TwitterControllerSpec extends Specification {<br \/>    TwitterReaderService twitterReaderServiceMock = Mock(TwitterReaderService)<br \/><br \/>    def setup() {<br \/>        controller.twitterReaderService = twitterReaderServiceMock<br \/>    }<br \/><br \/>    def \"show should redirect to index if TwitterError is thrown\"() {<br \/>        given:<br \/>            controller.params.id = '1'<br \/>        when:<br \/>            controller.show()<br \/>        then:<br \/>            1 * twitterReaderServiceMock.readTweet('1') >> { throw new TwitterError() }<br \/>            0 * _._<br \/>            flash.message == 'There was an error on fetching your tweet'<br \/>            response.redirectUrl == '\/twitter\/index'<br \/>    }<br \/>}<br \/><\/pre>\n<pre class=\"prettyprint\"><br \/>| Failure:  show should redirect to index if TwitterError is thrown(pl.refaktor.twitter.TwitterControllerSpec)<br \/>|  pl.refaktor.twitter.TwitterError<br \/> at pl.refaktor.twitter.TwitterControllerSpec.show should redirect to index if TwitterError is thrown_closure1(TwitterControllerSpec.groovy:29)<br \/><\/pre>\n<p>You may notice <code>0 * _._<\/code> notation. It says: <em>I don\u2019t want any other mocks or any other methods called. Fail this test if something is called!<\/em> It\u2019s a good practice to ensure that there are no more interactions than you want.<\/p>\n<p>Ok, now I need to implement controller logic to handle <code>TwitterError<\/code>.<\/p>\n<pre class=\"prettyprint\"><br \/>class TwitterController {<br \/><br \/>    def twitterReaderService<br \/><br \/>    def index() {<br \/>    }<br \/><br \/>    def show() {<br \/>        Tweet tweet<br \/><br \/>        try {<br \/>            tweet = twitterReaderService.readTweet(params.id)<br \/>        } catch (TwitterError e) {<br \/>            log.error(e)<br \/>            flash.message = 'There was an error on fetching your tweet'<br \/>            redirect(action: 'index')<br \/>            return<br \/>        }<br \/><br \/>        [tweet: tweet]    }<br \/>}<br \/><\/pre>\n<p>My tests passes! We have two scenarios left. Rule stays the same: <code>TwitterReaderService<\/code> returns something and we test against it. So this line is the heart of each test, change only returned values after <code>>><\/code>:<\/p>\n<pre class=\"prettyprint\"><br \/>1 * twitterReaderServiceMock.readTweet('1') >> { throw new TwitterError() }<br \/><\/pre>\n<p>Here is a complete test for three scenarios and controller that passes it.<\/p>\n<pre class=\"prettyprint\"><br \/>import grails.test.mixin.TestFor<br \/>import spock.lang.Specification<br \/><br \/>@TestFor(TwitterController)<br \/>class TwitterControllerSpec extends Specification {<br \/><br \/>    TwitterReaderService twitterReaderServiceMock = Mock(TwitterReaderService)<br \/><br \/>    def setup() {<br \/>        controller.twitterReaderService = twitterReaderServiceMock<br \/>    }<br \/><br \/>    def \"show should redirect to index if TwitterError is thrown\"() {<br \/>        given:<br \/>            controller.params.id = '1'<br \/>        when:<br \/>            controller.show()<br \/>        then:<br \/>            1 * twitterReaderServiceMock.readTweet('1') >> { throw new TwitterError() }<br \/>            0 * _._<br \/>            flash.message == 'There was an error on fetching your tweet'<br \/>            response.redirectUrl == '\/twitter\/index'<br \/>    }<br \/><br \/>    def \"show should inform about not found tweet\"() {<br \/>        given:<br \/>            controller.params.id = '1'<br \/>        when:<br \/>            controller.show()<br \/>        then:<br \/>            1 * twitterReaderServiceMock.readTweet('1') >> null<br \/>            0 * _._<br \/>            flash.message == 'Tweet not found'<br \/>            response.redirectUrl == '\/twitter\/index'<br \/>    }<br \/><br \/><br \/>    def \"show should show found tweet\"() {<br \/>        given:<br \/>            controller.params.id = '1'<br \/>        when:<br \/>            controller.show()<br \/>        then:<br \/>            1 * twitterReaderServiceMock.readTweet('1') >> new Tweet()<br \/>            0 * _._<br \/>            flash.message == null<br \/>            response.status == 200<br \/>    }<br \/>}<br \/><\/pre>\n<pre class=\"prettyprint\"><br \/>class TwitterController {<br \/><br \/>    def twitterReaderService<br \/><br \/>    def index() {<br \/>    }<br \/><br \/>    def show() {<br \/>        Tweet tweet<br \/><br \/>        try {<br \/>            tweet = twitterReaderService.readTweet(params.id)<br \/>        } catch (TwitterError e) {<br \/>            log.error(e)<br \/>            flash.message = 'There was an error on fetching your tweet'<br \/>            redirect(action: 'index')<br \/>            return<br \/>        }<br \/><br \/>        if (tweet == null) {<br \/>            flash.message = 'Tweet not found'<br \/>            redirect(action: 'index')<br \/>            return<br \/>        }<br \/><br \/>        [tweet: tweet]    }<br \/>}<br \/><\/pre>\n<p>The most important thing here is that we\u2019ve tested controller-service interaction without logic implementation in service! That\u2019s why mock technique is so useful. It decouples your dependencies and let you focus on exactly one subject under test. Happy testing!<\/p>\n","protected":false},"excerpt":{"rendered":"Even since I started to write tests for my Grails application I couldn&#8217;t find many articles on using mocks. Everyone is talking about tests and TDD but if you search for it there isn&#8217;t many articles.\nToday I want to share with you a test with mocks for a simple and complete scenario. I have a simple application that can fetch Twitter tweets and present it to user. I use REST service and I use GET to fetch tweets by id like this: http:\/\/api.twitter.com\/1\/statuses\/show\/236024636775735296.json. You can copy and paste it into your browser to see a result.\nMy application uses Grails 2.1 with spock-0.6 for tests. I have TwitterReaderService that fetches tweets by id, then I parse a response into my Tweet class.\nclass TwitterReaderService {    Tweet readTweet(String id) throws TwitterError {        try {            String jsonBody = callTwitter(id)            Tweet parsedTweet = parseBody(jsonBody)            return parsedTweet        } catch (Throwable t) {            throw new TwitterError(t)        }    }    private String callTwitter(String id) {        \/\/ TODO: implementation    }    private Tweet parseBody(String jsonBody) {        \/\/ TODO: implementation    }}class Tweet {    String id    String userId    String username    String text    Date createdAt}class TwitterError extends RuntimeException {}\nTwitterController plays main part here. Users call show action along with id of a tweet. This action is my subject under test. I&#8217;ve implemented some basic functionality. It&#8217;s easier to focus on it while writing tests.\nclass TwitterController {    def twitterReaderService    def index() {    }    def show() {        Tweet tweet = twitterReaderService.readTweet(params.id)        if (tweet == null) {            flash.message = 'Tweet not found'            redirect(action: 'index')            return        }        [tweet: tweet]    }}\nLet&#8217;s start writing a test from scratch. Most important thing here is that I use mock for my TwitterReaderService. I do not construct new TwitterReaderService(), because in this test I test only TwitterController. I am not interested in injected service. I know how this service is supposed to work and I am not interested in internals. So before every test I inject a twitterReaderServiceMock into controller:\nimport grails.test.mixin.TestForimport spock.lang.Specification@TestFor(TwitterController)class TwitterControllerSpec extends Specification {    TwitterReaderService twitterReaderServiceMock = Mock(TwitterReaderService)    def setup() {        controller.twitterReaderService = twitterReaderServiceMock    }}\nNow it&#8217;s time to think what scenarios I need to test. This line from TwitterReaderService is the most important:\nTweet readTweet(String id) throws TwitterError\nYou must think of this method like a black box right now. You know nothing of internals from controller&#8217;s point of view. You&#8217;re only interested what can be returned for you:\n\na TwitterError can be thrown\nnull can be returned\nTweet instance can be returned\n\nThis list is your test blueprint. Now answer a simple question for each element: &#8220;What do I want my controller to do in this situation?&#8221; and you have plan test:\n\nshow action should redirect to index if TwitterError is thrown and inform about error\nshow action should redirect to index and inform if tweet is not found\nshow action should show found tweet\n\nThat was easy and straightforward! And now is the best part: we use twitterReaderServiceMock to mock each of these three scenarios!\nIn Spock there is a good documentation about  interaction with mocks. You declare what methods are called, how many times, what parameters are given and what should be returned. Remember a black box? Mock is your black box with detailed instruction, e.g.: I expect you that if receive exactly one call to readTweet with parameter &#8216;1&#8217; then you should throw me a TwitterError. Rephrase this sentence out loud and look at this:\n1 * twitterReaderServiceMock.readTweet('1') &gt;&gt; { throw new TwitterError() }\nThis is a valid interaction definition on mock! It&#8217;s that easy! Here is a complete test that fails for now:\nimport grails.test.mixin.TestForimport spock.lang.Specification@TestFor(TwitterController)class TwitterControllerSpec extends Specification {    TwitterReaderService twitterReaderServiceMock = Mock(TwitterReaderService)    def setup() {        controller.twitterReaderService = twitterReaderServiceMock    }    def \"show should redirect to index if TwitterError is thrown\"() {        given:            controller.params.id = '1'        when:            controller.show()        then:            1 * twitterReaderServiceMock.readTweet('1') &gt;&gt; { throw new TwitterError() }            0 * _._            flash.message == 'There was an error on fetching your tweet'            response.redirectUrl == '\/twitter\/index'    }}\n| Failure:  show should redirect to index if TwitterError is thrown(pl.refaktor.twitter.TwitterControllerSpec)|  pl.refaktor.twitter.TwitterError at pl.refaktor.twitter.TwitterControllerSpec.show should redirect to index if TwitterError is thrown_closure1(TwitterControllerSpec.groovy:29)\nYou may notice 0 * _._ notation. It says: I don&#8217;t want any other mocks or any other methods called. Fail this test if something is called! It&#8217;s a good practice to ensure that there are no more interactions than you want.\nOk, now I need to implement controller logic to handle TwitterError.\nclass TwitterController {    def twitterReaderService    def index() {    }    def show() {        Tweet tweet        try {            tweet = twitterReaderService.readTweet(params.id)        } catch (TwitterError e) {            log.error(e)            flash.message = 'There was an error on fetching your tweet'            redirect(action: 'index')            return        }        [tweet: tweet]    }}\nMy tests passes! We have two scenarios left. Rule stays the same: TwitterReaderService returns something and we test against it. So this line is the heart of each test, change only returned values after &gt;&gt;:\n1 * twitterReaderServiceMock.readTweet('1') &gt;&gt; { throw new TwitterError() }\nHere is a complete test for three scenarios and controller that passes it.\nimport grails.test.mixin.TestForimport spock.lang.Specification@TestFor(TwitterController)class TwitterControllerSpec extends Specification {    TwitterReaderService twitterReaderServiceMock = Mock(TwitterReaderService)    def setup() {        controller.twitterReaderService = twitterReaderServiceMock    }    def \"show should redirect to index if TwitterError is thrown\"() {        given:            controller.params.id = '1'        when:            controller.show()        then:            1 * twitterReaderServiceMock.readTweet('1') &gt;&gt; { throw new TwitterError() }            0 * _._            flash.message == 'There was an error on fetching your tweet'            response.redirectUrl == '\/twitter\/index'    }    def \"show should inform about not found tweet\"() {        given:            controller.params.id = '1'        when:            controller.show()        then:            1 * twitterReaderServiceMock.readTweet('1') &gt;&gt; null            0 * _._            flash.message == 'Tweet not found'            response.redirectUrl == '\/twitter\/index'    }    def \"show should show found tweet\"() {        given:            controller.params.id = '1'        when:            controller.show()        then:            1 * twitterReaderServiceMock.readTweet('1') &gt;&gt; new Tweet()            0 * _._            flash.message == null            response.status == 200    }}\nclass TwitterController {    def twitterReaderService    def index() {    }    def show() {        Tweet tweet        try {            tweet = twitterReaderService.readTweet(params.id)        } catch (TwitterError e) {            log.error(e)            flash.message = 'There was an error on fetching your tweet'            redirect(action: 'index')            return        }        if (tweet == null) {            flash.message = 'Tweet not found'            redirect(action: 'index')            return        }        [tweet: tweet]    }}\nThe most important thing here is that we&#8217;ve tested controller-service interaction without logic implementation in service! That&#8217;s why mock technique is so useful. It decouples your dependencies and let you focus on exactly one subject under test. Happy testing!\n","protected":false},"author":37,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[50,30,364],"class_list":{"0":"post-12274","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-development-design","7":"tag-groovy","8":"tag-testing","9":"tag-tests"},"_links":{"self":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12274","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/users\/37"}],"replies":[{"embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/comments?post=12274"}],"version-history":[{"count":3,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12274\/revisions"}],"predecessor-version":[{"id":14359,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/posts\/12274\/revisions\/14359"}],"wp:attachment":[{"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/media?parent=12274"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/categories?post=12274"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/touk.pl\/blog\/wp-json\/wp\/v2\/tags?post=12274"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}