Testing GWTP applications with Jukito – Introduction to TDD

This is the first blog post of a series that will evolve into a step-by-step guide for testing GWTP applications using TDD.

The goal of this first post is to give the readers basic knowledge that will serve as the foundation for the rest of the series.

Prerequisites

In order to understand this post and apply the ideas that it contains, you should:

  • Know how to use JUnit
  • Understand the fundamentals of TDD [Red-Green-Refactor]

Post_Jukito_TestingTDD_v1-02

This post includes an overview of the following topics and also provides references for further details :

  • Classic vs Mockist TDD
  • Dependency Injection

Classic vs Mockist TDD

This section is not made to bash either type of TDD or to say that one is better than the other. It is meant to show the strengths and the weaknesses of each type and to show the context in which each of them is relevant. The two styles are not mutually exclusive, but rather complementary.

Classic TDD

This approach was first popularized by Kent Beck. The idea behind this kind of TDD is to test an algorithm multiple times by using different inputs and validating the outputs. Typically, this involves having tests on a class and hiding what’s happening in the background, i.e. hiding the direct dependencies of the class under test.

For example, if the class’ outputs are only dictated by its inputs, then a classic TDD test is easy to write. (e.g. to test a sorting algorithm, you just have to give it multiple inputs and have the corresponding expected outputs to verify it).

Unfortunately, not all situations are like that. Take for example an application that fetches data from an external source like a web API. Testing this involves more than checking outputs based on specific inputs. The actual output of the class will depend on its environment.

Mockist TDD

Mockist TDD – also called London School TDD – approach was popularized by Steve Freeman and Nat Pryce, and is focused on verifying the interactions of a class within its ecosystem. It is also a good tool for driving the design of an application.

One of the strengths of Mockist TDD is that it helps us organize the layers and the dependencies of an application. For example, many tests written using this kind of TDD will involve checking that a class delegates an action to the correct collaborator with the correct values. Other tests might consist in verifying that the tested class reacts correctly to its collaborators’ responses.

These kinds of tests help demonstrate that the communication doesn’t bypass layers in the application. It also helps ensuring that the Tell don’t ask principle is respected.

When testing GWTP applications, these concepts are very useful, because most testing will be interaction oriented.

Here’s a demonstration of J.B. Rainsberger developing an application using Mockist TDD.

Dependency Injection

Most of the time, when a class starts doing too much job, it is wise to split it up in smaller pieces. When testing a class, one of the best practices is to isolate it from the outside world (anything too complex, unpredictable or that doesn’t belong in the same level of abstraction).

Here’s a quote from James Shore that defines Dependency Injection :

“Dependency Injection” is a 25-dollar term for a 5-cent concept. That’s not to say that it’s a bad term… and it’s a good tool. But the top articles on Google focus on bells and whistles at the expense of the basic concept. I figured I should say something, well, simpler.

[…]

Dependency injection means giving an object its instance variables. Really. That’s it.

Basically, this lets us control the outside environment. For example, given a class “A" that makes an HTTP request to an API and uses the data to do some computation, the constructor of A would receive an instance of the class B that is responsible of making that HTTP request. Class A would only use the data provided by B.

In a testing context, one could pass an instance of B to A with controlled and predictable return values.

There are multiple ways of making objects behave in a controlled/predictable way. Such objects are usually called “test doubles”. In testing jargon, the different types of test doubles are:

  • Stub
  • Mock
  • Dummy
  • Fake

Martin Fowler has written a good reference on the different types of test doubles. Mark Seeman has also written an excellent article explaining when to use Mocks and Stubs.

In a Mockist TDD context, one would pass A‘s collaborators by constructor parameters and then test the behaviour of A when it interacts with them. Such behaviour can be verified using a mock object.

A Mock is an object that has expectations of interactions with other objects. It is used to verify that a call which was expected to happen really did happen.

Examples

The tools used for the examples are:

Classic TDD

As said before, classic TDD is easier to use in an algorithm context. Let’s take as an example the Leap Years Kata.

Write a function that returns true or false depending on whether its input integer is a leap year or not.

A leap year is defined as one that is divisible by 4, but is not otherwise divisible by 100 unless it is also divisible by 400.

For example, 2001 is a typical common year and 1996 is a typical leap year, whereas 1900 is an atypical common year and 2000 is an atypical leap year.

A typical code base written with classical TDD would end up with several test cases trying different inputs and expecting specific outputs.

Mockist TDD

It is hard to come up with simple examples that illustrate where mockist TDD really shines. We will try to do it with an example involving a Web API. Let’s imagine an endpoint that returns a username when it is given the user’s id.

Some people would arguably remove the first test because the behaviour it is verifying is also covered in the other tests. This is a matter of personal preference.

The design that emerges from these tests is directly linked to the use of mockist TDD, and by the objective of getting a piece of code that’s as easy as possible to test. This is where the collaborating classes (the factory and the user information service) came from.

What should I use?

There’s unfortunately no definitive answer. Both are good, just in different situations. It’s mostly a question of trade-offs and of preference. Here are a few points to consider:

Generally

  • Classic TDD is better suited for algorithm testing
  • Mockist TDD is better suited for to check interactions between components of a system
  • Mockist TDD will create many collaborating classes early in the process. Classic TDD will push the creation of collaborators to later in the process.
  • A code base written with mockist TDD is harder to refactor because a change in a collaborator’s API is likely to break a test.
    • Some people suggest looking into ATDD to help with this problem.
  • A code base written with classic TDD is easier to refactor; an implementation change doesn’t break tests
  • Mockist TDD leads to an end-to-end implementation easily when using a Walking Skeleton.

Conclusion

Classic TDD works better when testing algorithms and Mockist TDD when verifying interactions between the components of a system.

Using dependency injection typically reveals a class’ dependencies explicitly, and allows us to substitute them easily with objects having controlled and predictable behaviours (test doubles).

The purpose of this post was to introduce the fundamental ideas that will serve as building blocks for later articles in this series. Don’t worry, there will be more code and less theory in the future posts.

The next article will be an overview of Jukito, a library built on top of JUnit and Mockito. Knowing how to use Jukito is pretty important. Although it is not strictly necessary for testing GWTP applications, it will be used for the rest of the series, since it saves a lot of time.

Subscribe to our newsletter to be notified when the next post comes out!

Happy Testing!

Other good references

How to use GWTChosen in a GWT application

To follow up on our blog post about the release of GWTChosen 3.0 last week, we wanted to offer a little tutorial on how to use GWTChosen in a GWT or GWTP application.

Dependencies

Suppose you are using Maven on a regular GWT application (if you are not using Maven, you’ll need to have the JARs of these dependencies installed in your PATH).

There are 3 dependencies that you need. First, GWTChosen depends on GQuery, so you’ll need to have GQuery among them. You’ll also need Guava-GWT (for the Collect GWT Module) and the GWTChosen dependency itself.

It should look like this (in your pom.xml) :

Install the GWT Modules

You’ll also have to install the GWT Module corresponding to the GWTChosen dependency :

<inherits name="com.arcbees.chosen.Chosen"/>

Load GWTChosen

Once these steps are complete, you’re ready to use GWTChosen.

If you are using the widget in UiBinder, you’ll need to add this line in the opening XML UiBinder tag :

xmlns:chzn="urn:import:com.arcbees.chosen.client.gwt"

In UiBinder, when you want to declare it, you are then able to write something like this :

The Simple Chosen widget is now on your page.

If we want to use the Multiple Values Chosen instead, it will take a bit more work. We have to declare it dynamically (which is also possible with the Simple Value option). We only declare the object in the UiBinder, but not the values and the parameters :

Here’s an example of what we can do in our Java class as a result (this example is with GWTP, but it would be exactly the same idea with pure GWT) :

Now you have a Chosen Widget where you’ll be able to select multiple elements, and dynamically add or remove elements, if you want.

I hope this helped clarify how GWTChosen works, and how to set it up. If you want the detailed code for this example, you can find it here on GitHub. For more details and additional features, explore our documentation.

If you have any other questions about GWTChosen, there will be a Q&A with Maxime and I next week. We look forward to meeting you online and answering any questions you may have.

Also, don’t forget to subscribe to our newsletter to be informed when there is new content on our blog!

GWTChosen 3.0 and an upcoming Q&A on this release

Erratum on the event date: It will be held on October the 7th with Maxime and Olivier from Arcbees on this release

We’re happy to announce the latest major update of GWTChosen – version 3.0.

This release includes a mobile version of GWTChosen. The full release notes on GitHub describe it in detail. The whole purpose of GWTChosen has been to make long, unwieldy select boxes user-friendly. However, the mobile experience still wasn’t smooth enough, so we refactored the code. Now mobile users can enjoy the same ease of use that GWTChosen gave people on larger screens.

If we compare the desktop and the mobile version of Chosen, we see that each one is a good fit for its context of use.

Single Chosen on desktop :

single-desktop

Single Chosen on mobile

single-mobile

Multiple Chosen on desktop

multiple-desktop

Multiple Chosen on mobile

multiple-mobile

If you’re not sure how to include GWTChosen in your project, check out the documentation. We made it as easy to include as we possibly could (hint : it’s a one-liner ;-)).

As Philippe said in his last blog post, we will start a series of Q&A sessions with leading lights in the GWT Universe. First up will be on the release of GWT Chosen. It will be held next week for a live Q&A on October 7th! You can already register for the event here.

Subscribe to our newsletter to receive more articles of this type in your inbox. Stay tuned for a follow-up article on how to use the GWTChosen custom styling properties.

New release for GWTP and its IntelliJ plugin!

Last week, we organized our first hackathon ever. It was two days of real fun, focusing on the core of our business : our open source projects.

To help make it even more fun, we assigned team different colors. Each one could win points and leaders could “punish” other teams (mostly making bottom teams serve Mr. Freezes and beer to the other teams ;-)).

Post_GWTP_Release_1.5_v1-05

The two main focus of the developers were to release the 1.5 version of GWTP (which has been in the making for a few weeks) and to solidify and update the IntelliJ plugin.

Mission Accomplished! It’s time to unveil the latest creations from our team at Arcbees and our many external contributors.

Post_GWTP_Release_1.5_v1-01

One feature of this release is simplified boilerplate for nested presenters. We don’t need the @ContentSlot annotation anymore. It is now replaced by a NestedSlot type. The @ContentSlot still works but is now deprecated. You can read more about this new slot mechanism on our developer portal.

We also added name token configuration to the DefaultModule builder. As always, we also improved our Rest-Dispatch to be even more useful to our users.

The complete release notes and list of contributors are shown in the GitHub repo.

Post_GWTP_Release_1.5_v1-03

For those of you that were using the IntelliJ plugin, there was a nasty bug that prevented the user from creating a project with the newest archetype and the newest version of IntelliJ. So, it was the first thing we worked on during the first day of the hackathon.

Post_GWTP_Release_1.5_v1-06

Next, we improved the user experience of the Create Presenter dialog to make it simpler and to make it more clear to describe what is going on.

Post_GWTP_Release_1.5_v1-04

You can download the last version on the JetBrains plugin repository.

Also, if you prefer to use Maven alone, we just released a short video on how to start a new GWTP project (french version here). Fundamentally, it is the same process the plugin uses when creating a new project : executing the Maven instruction to generate the archetype from a Sonatype repository.

As you can see, the goal of this release is to simplify your GWTP experience as much as possible.

Thanks for your invaluable feedback. It helps us create products that are relevant in real use cases and that immensely simplify a developer’s daily work.

If you’re curious about where we are going with the next major version of GWTP, you can watch this presentation that Christian Goudreau gave at the last GWT.create. He was talking about how to improve your productivity with GWTP, but he gives a glimpse at the end of the talk about what lies ahead for GWTP.

Stay tuned for more to come and feel free to let me know how we can help you become more efficient with this framework.

The bees need your thoughts on GAE-Studio!

As our product evolves, we rely on frequent feedback from users to stay aligned on what you really want and need as developers.

We want to make a tool that will help you be more productive and drive down development costs.

We would really appreciate it if you would take a few minutes to help us by filling out the following survey.

https://docs.google.com/forms/d/1rllmpTb_rzygXqo-z7DsyzOqfeqeUoFxjmcWRK6qPV8/viewform


Thanks so much! It really means a lot to us. We pay enormous attention to every idea you share.

Jukito 1.4 and GWTP 1.2.1

In parrallel with the development of our next major commercial product, our ninja developers continue to work on our open source projects. We love working in the trenches of web application development. It’s what gives us the perspective we need to build the best web framework and tools we can.

Your feedback is our most valuable guidance. It helps us polish our software and even inspires us to develop entirely new and unforeseen features !

Jukito 1.4

We’re proud to announce a new version of Jukito with three new kinds functionalities: support for private modules, ability to override the UseModules declaration, and inheritance of the UseModules annotation.

Here are the details of the changes on GitHub :

Added support for PrivateModules in the JukitoRunner

Enabling the use of UseModules on methods to override class level

Allow inheritance of @UseModules

GWTP 1.2.1

We’re also proud to release a new version of GWTP, which is compatible with the newest GWT 2.6. Also, you can now have access to the project information quickly by going to http://arcbees.github.io/GWTP/. Please give us feedback to help us improve the information published on this website with each future release.

We fixed a few failing tests and updated some librairies to get things right with GWT 2.6. Starting with 1.2.1, the build process will also display a warning if a newer version of GWTP is available.

We improved the Route Token Formatter by allowing the hashbang (#!/), so web crawlers can recognize your tokens. We also moved some classes to a shared package so you can reuse  the route token formatter from your server code. Please see the migration notes as the latter is a breaking change.

The Rest Dispatch project also got a load of new features. Most of them are configuration methods to help illuminate your development journey. The exhaustive list is available in the release notes, but we’ll review some of the key changes:

  • The CSRF protection header can be disabled on specific calls by using a new annotation.

  • It’s now possible to configure parameters that will be added automatically to your calls without specifying them in your service interface. Those parameters can be filtered out by HTTP method and parameter type.

  • We added some support for formatting dates.

You can see the release notes here or the details of the key commits on GitHub:

Changed version for Guava and Gin

Fixing CarStore’s selenium tests

Update gwt-jackson to 0.4.0

Fixing CarStore and selenium tests

Improved the ability to configure the serialization mechanism

Rest-Dispatch: Support for Sub-Resources

Retrieve the latest version and compare it when compilation

Custom request timeout configuration

Allow specific unsecured REST calls when SecurityCookie is bound

Move PlaceRequest and TokenFormatters to mvp-shared

Improvements to Route Token Formatter

Added customization methods for global Query and Header parameters

Fixed Fix Multimap Serialization

Fixed some checkstyle warnings

Allows interfaces compositions when creating RestService

Configurable date formats for resource parameters

In particular, thanks to aldenquimby, christiangoudreau, Chris-V, diamondq, jDramaix, meriouma, nmorel, olafleur, PhilBeaudoin, spg and tonuquq for this awesome release!

GAE-Studio Newsletter #6

The agile Bees are working really hard to develop the best tool ever for working with Google App Engine. We want to make using the GAE stack easy and fun. We’re happy to announce the release of GAE-Studio 0.8.1, the latest version of our rapidly evolving GAE development environment !

What to expect in this newest version?

We have completed the redesign of the application that we initiated a few weeks ago. We also added a logout button and tweaked some of the feedback/error messages to improve your user experience, which is always important to us.

At a technical level, we have added a much-requested feature : the ability to import and export data from Google App Engine. At the moment, there’s an import limit of 2 Gb, due to the limitations of GAE Blobstore, but within that limit the import/export feature works. Additionally, we fixed an issue with the prior version of GAE Studio which did not allow people to activate email addresses containing a “+” character.

A quick warning note : we’re planning to refactor our authentification API in the next iteration of GAE-Studio, so when we will release 0.9, you will need to update to the newest version.

As usual, thanks for reporting any issues that you find when working with GAE Studio. That feedback is our most powerful resource for making the software better. We’d love to hear more! If you have a few minutes today, please let us know what you like most about GAE-Studio, what you like least, and what features you’d like us to add. We appreciate your advice. Drop us an email or use the issue tracker to let us know what you think.

Thanks a lot and we look forward to your feedback !

 

GAE-Studio Newsletter #5

(Version française à la suite)

Good morning fellow developers !

In business news, we greeted yesterday a new bee : Joël Trottier-Hébert, who will enhance our team by focusing on integration tests in our projects, including GAE-Studio.

In product news, we’re proud to announce our first version of GAE-Studio for 2014, GAE-Studio 0.7 !

We have started releasing GAE-Studio to Maven Central, a long awaited feature, which will be a lot more convenient than downloading a jar for every new version. 😉

You can already find our newest version on Maven.

On the functionality side, we switched from RestyGWT to RestDispatch. We also added a lot more user feedback to the UX, which we think is really important when developing something that we want people to use a lot and often.

As promised, our new UI is really kicking ass. Please tell us if you like it ! It’s a work in progress, but we think it’s moving in the right direction to make GAE-Studio an application that will be easy and fun to use.

Also, we’ve sent a new wave of invites to the  GAE-Studio beta group. We now have quite a few of you and we really appreciate the feedback that we’re receiving. Please continue to send it !

If you have suggestions or issues, let’s talk in the issue tracker ! We really look forward to any opportunity to provide help or be of service.

Here are a few screenshots of the new user experience. Give it a try today ! You won’t regret it.

Visualizer
profiler
Profiler

————————————————

Bon matin à vous, chers développeurs!

Tout d’abord, une nouvelle d’entreprise puisque hier une nouvelle abeille s’est jointe à nous, soit Joël Trottier-Hébert. Joël ajoutera une plus-value à notre équipe en se concentrant sur les tests d’intégration de nos différents projets, dont GAE-Studio.

Ensuite, côté produits, nous sommes très fiers d’annoncer notre première version de GAE-Studio de 2014, GAE-Studio 0.7!

De plus, nos nouvelles versions sont maintenant disponibles sur Maven Central, une fonctionnalité attendue depuis longtemps. Beaucoup plus pratique que de télécharger un fichier .jar à chaque nouvelle version. 😉

Vous pouvez déjà y retrouver notre version 0.7.

Côté fonctionnalités, nous sommes passés de RestyGWT à RestDispatch. Nous avons aussi ajouté beaucoup de feedback à l’expérience utilisateur, une modification essentielle pour quiconque veut que son produit soit davantage utilisé.

Tel que promis, notre nouvelle interface usager est vraiment superbe. Merci de nous dire si vous l’aimez ! Ce n’est qu’un début, mais nous pensons que nous sommes dans la bonne direction pour faire de GAE-Studio une application agréable et facile d’utilisation.

Aussi, nous avons envoyé une nouvelle vague d’invitations à GAE-Studio. Nous avons constitué une bonne liste de béta-testeurs et nous apprécions réellement les commentaires que nous recevons. Continuez à partager avec nous!

Si vous avez des suggestions ou des problèmes, n’hésitez pas à le mentionner dans notre gestionnaire d’incidents. Laissez-nous vous aider!

Voici quelques captures d’écran de la nouvelle expérience utilisateur. Essayez GAE-Studio aujourd’hui. Vous ne le regretterez pas.

Visualizer
profiler
Profiler

GWTP 1.1 is here !

I hope you’re having a good time at GWT.create !

We’re closing our round of annoucements with the release of a new version of our flagship product : GWTP.

In this release, we mostly focused on the dispatch projects. The REST Dispatch has had its serialization dependency updated to a library compatible with Jackson 2 annotations.

Also, all dispatch projects were cleaned up. As a side effect, the RPC dispatch artifacts were renamed and most of the code was moved to new packages. Whilst the old code is still there, it has been deprecated. We will write a migration guide to help you update your application so you don’t face major issues when we remove that code in the next major release.

What’s next for GWTP? For sure, one of our top priorities is to support the new GWT 2.6 .

We have big plans for that product, but your feedback and ideas are always welcome. We want to make that product fit your needs.

Thanks a lot to all the contributors in this release, but a special thanks to branflake2267, Chris-V, christiangoudreau, jDramaix, meriouma, nmorel, spg and StetsenkoEM

The team at ArcBees would like to wish you and your family happy holidays. Take some time to relax and be with your family.

We’ll be back in 2014 and ready to tackle big new projects !

Here are the details of this release :

Glass fix for IE

Add extension points to the REST dispatch code

Removed the compile warnings about JAX-RS annotations

Deprecated the old RPC dispatch code

Extracted common code between RPC and REST Dispatch projects

Added some javadoc to the REST dispatch project

Replaced the REST serialization library from piriti to gwt-jackson

Added the new dispatch dependencies to gwtp-all

Dispatch Projects Update (summary of the changes introduced in the dispatch projects)

 

An IntelliJ plugin for GWTP

The day that you finally waited for is upon us ! Fans of GWTP and IntelliJ, a new plugin is here !

You will be able to combine the power of our favorite editor, IntelliJ, with the power of our favorite web framework, GWTP. That’s almost a super-power !

You want to know how it works? Our bee Brandon Donnelson has made videos to show you how.

Here’s how to install the plugin and create a GWTP project :

[youtube=http://www.youtube.com/watch?v=s_HOmpuouEo&w=420&h=315]

And here’s how to create a presenter :

[youtube=http://www.youtube.com/watch?v=_u03xsCYpS0&w=560&h=315]

You can download it here !

And we know a few of you coders are interested in how it’s done. You can see the code (and even contribute !) on Github.

If you have some time during your holiday vacations, try it and give us feedback on your ideas to improve it !