Opportunity to grow

In 2022, in addition to the work we do for our clients, we put our heads together and organized events and activities that would help us further develop our skills and knowledge, while providing a healthy break from our daily tasks. What follows is a brief account of what we planned, what worked and what didn’t.

Book Santa

We started the new year with gifts. Everyone could order a book, an actual physical book made of paper and ink, the only condition was that it be “at least a little work-related”. The idea was well received and orders soon poured in. The logistics involved in collecting titles from 130 people, ordering and then sending them to those who work more often remotely proved something of a challenge, but somehow we managed. Only one book from the UK got irretrievably stuck in customs (thanks, Brexit!). I don’t know how many books were read – since they were gifts, it didn’t seem appropriate to ask! – but I do know that one of them is currently being used as a monitor stand. An unexpectedly fascinating side effect of the scheme was being able to take a look at the freely available excel sheet and see who had ordered what and to learn about books you’d previously been unaware of.

Flashtalks

We meet once a month on a Friday to hear three people from the company, usually developers, give short presentations. Ensuring that every month there are enough volunteers willing to talk about something technical or somehow related to our work is no mean feat. Persuading, encouraging, twisting the arms of busy colleagues is a major challenge for the organizers of these talks. Occasionally, these talks cover less technical areas and we get the chance to learn about advantages of giving and receiving feedback, money saving and how to become a conference speaker. The purpose of Flashtalks is to both share knowledge and create a space where presentation skills can be practiced and honed in front of a larger audience. In 2022 there were 29 speakers (seven of whom spoke twice) and 36 presentations altogether. Topics ranged from “How to monitor applications after deployment” to “Will Niagara Files work on the Mississippi” and “DIY simple lab power supply”. Both novice developers as well as senior conference veterans share their wisdom. One of the great things about Flashtalks is the post-talk questionnaire, which always provides us with valuable feedback on what went well and what could be done better. Each Flashtalk ends with a quiz, which introduces an element of gamification and prevents Flashtalks from becoming merely a chance to take a break from work.

One of the aims of the Flashki is to create new conference speakers. This year Monika Fus made her debut at Confitura, an event very much close to our hearts, where she spoke about “L10n, i18n and t9n in the JVM world”. Other speakers included Piotr Fus with his presentation “How to get started with metrics”, Maciek Próchniak with “Well, it’s time to synchronize watches” and Dominik Przybysz with “OOP Revisited”. The whole team traveled around Poland and beyond with their presentations. Check them out here: https://touk.pl/talks/2022. While we had hoped there would be more newcomers in 2022, we are confident that 2023 will see a greater number of conference debuts.

Dojo

TouK Dojo is a more hands-on learning initiative that one of the developers came up with this year. We hold technical workshops for each other and meetings where we solve problems, often algorithmic. It’s a good opportunity to bounce ideas off each other about how to do things, try out tools, ask questions and work on real examples. Meetings usually take place once a week, live and online.

Blog

In April, as a grassroots initiative, a few of us set a goal to post monthly on our company blog. We wanted to restore it to its former glory, or perhaps just revive it after the drought years of the pandemic. We almost succeeded, with our combined efforts resulting in six posts about hackathons, a summary of the first post-pandemic Confitura, and of course some technical posts. We are now thinking about how to take the initiative further. It seems that the valuable content we could share is there, but we need to find the time and a way to overcome writer’s block.

Hackathons

Last year we organized a couple of hackathons: one in the spring and one in the autumn. We had initially considered having four in the space of a year, but that turned out to be a bit too ambitious, given the amount of work we do for our clients and the number of ideas to hack. The general framework developed in battle is: two days in our office, any project, any team composition, pizza and snacks for all. You can read detailed descriptions of what we achieved here: https://touk.pl/blog/2022/05/12/touk-hackathon-toukathon-april-2022/ and https://touk.pl/blog/2022/11/28/toukathon-october-2022/. In spring sixteen people coded together, in autumn eight.

Books

It has always been possible for any employee to order books for our shared library. Perhaps because of the number of books gifted at the start of the year, the number of books ordered during the year was a little smaller than normal. Still, our library has now been enriched with:

  • Diagnosing and Changing Organizational Culture: Based on the Competing Values Framework, Kim S. Cameron, Robert E. Quinn
  • The Enterprise Big Data Lake, Alex Gorelik
  • The Java Module System, Nicolai Parlog
  • Bulletproof TLS and PKI 2ed, Ivan Ristić
  • Job crafting nowa metoda budowania zaangażowania i poczucia sensu w pracy, Malwina Puchalska-Kamińska, Agnieszka Łądka- Barańska
  • Functional programming in Scala second edition, Paul Chiusano, Runar Bjarnason
  • Functional Design and Architecture v7, Alexander Granin
  • Functional Event-Driven Architecture, Gabriel Volpe
  • Code, Charles Petzold

Since January is time for resolutions, here are ours. This year we want to continue the Flashki (the first has already taken place on 20 January), we will confidently hack together, and we are already planning a calendar of speeches at conferences.

You May Also Like

How to use mocks in controller tests

Even since I started to write tests for my Grails application I couldn't find many articles on using mocks. Everyone is talking about tests and TDD but if you search for it there isn't many articles.

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: http://api.twitter.com/1/statuses/show/236024636775735296.json. You can copy and paste it into your browser to see a result.

My 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.


class 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 {}

TwitterController plays main part here. Users call show action along with id of a tweet. This action is my subject under test. I've implemented some basic functionality. It's easier to focus on it while writing tests.


class 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]
}
}

Let'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:


import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(TwitterController)
class TwitterControllerSpec extends Specification {
TwitterReaderService twitterReaderServiceMock = Mock(TwitterReaderService)

def setup() {
controller.twitterReaderService = twitterReaderServiceMock
}
}

Now it's time to think what scenarios I need to test. This line from TwitterReaderService is the most important:


Tweet readTweet(String id) throws TwitterError

You must think of this method like a black box right now. You know nothing of internals from controller's point of view. You're only interested what can be returned for you:

  • a TwitterError can be thrown
  • null can be returned
  • Tweet instance can be returned

This list is your test blueprint. Now answer a simple question for each element: "What do I want my controller to do in this situation?" and you have plan test:

  • show action should redirect to index if TwitterError is thrown and inform about error
  • show action should redirect to index and inform if tweet is not found
  • show action should show found tweet

That was easy and straightforward! And now is the best part: we use twitterReaderServiceMock to mock each of these three scenarios!

In 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 '1' then you should throw me a TwitterError. Rephrase this sentence out loud and look at this:


1 * twitterReaderServiceMock.readTweet('1') >> { throw new TwitterError() }

This is a valid interaction definition on mock! It's that easy! Here is a complete test that fails for now:


import grails.test.mixin.TestFor
import 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') >> { throw new TwitterError() }
0 * _._
flash.message == 'There was an error on fetching your tweet'
response.redirectUrl == '/twitter/index'
}
}

| 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)

You may notice 0 * _._ notation. It says: I don't want any other mocks or any other methods called. Fail this test if something is called! It's a good practice to ensure that there are no more interactions than you want.

Ok, now I need to implement controller logic to handle TwitterError.


class 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]
}
}

My 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 >>:


1 * twitterReaderServiceMock.readTweet('1') >> { throw new TwitterError() }

Here is a complete test for three scenarios and controller that passes it.


import grails.test.mixin.TestFor
import 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') >> { 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') >> 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') >> new Tweet()
0 * _._
flash.message == null
response.status == 200
}
}

class 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]
}
}

The most important thing here is that we've tested controller-service interaction without logic implementation in service! That's why mock technique is so useful. It decouples your dependencies and let you focus on exactly one subject under test. Happy testing!