Inject mocks with Spring’s @ContextConfiguration

One of the biggest strengths of Spring is its ability to make your code testable. By using dependency injection and inversion of control, the Spring context defines which objects will be wired into your beans. This makes it easy to wire services, repositories or what ever you like. But how to wire mocks in your tests?

Example

Let’s create a simple test setup: we have a service called OrderService which handles orders from customers. To do this, the OrderService needs a BillingService.

A typical test setup would run the Spring context, auto-wire the OrderService and test it. But if we would do so, we would also need to include the BillingService into the Spring context. And if the BillingService would need some other service, we would need to include this too and each and every transitiv dependency. Maybe we would end up by loading your whole app just to test one simple service.

A test setup with mocks

Whenever you want Spring to inject our beans, you must create a Spring context. Every bean you want to use must be part of this context as well as every transitiv bean. In this case we need two bean: (1) the OrderService which we want to test and the (2) BillingService which is a transitiv dependency. Both beans must be part of the Spring context!

However, we don’t want to use the real BillingService but a mock. To do this, we provide a dedicated @Configuration for our test which returns such a mock (with Mockito). If we would have other dependencies, we would do this for every bean used by the OrderService.

This makes it possible to load a very small Spring context: We only need our class to test and a mock very each of its dependencies. This is more like an unit test but an integration test and will run very fast. But the nice thing is, that you can decide which dependencies you want to mock and which not. If you would like to mock the BillingService but not the CustomerService it fine. You can control the amount of mocks very easily.

Best regards,
Thomas

Use ranges with ngRepeat

ngRepeat

Angular’s ngRepeat directive provides a simple way to iterate over collections to produce HTML dynamically. You probably know it when you have ever worked with lists or arrays in your Angular app:

Drawbacks

However, there is a small drawback when working with ngRepeat: You can only iterate over collections of the current scope. Loop definitions (like a typical for-loop) are not supported. This means you cannot to something like this:

The solution

But there is a simple trick to build a workaround for this. If you use a library like Lodash.js or Underscore.js the trick becomes even more simple: As ngRepeat requires a function on the scope, we just provide such a function!

That’s all we need. If we append Lodash/Underscore to our scope, we can use the library within our partials. This might looks like this:

Keep in mind

With great power comes great responsibility. When we append Lodash/Underscore to the Angular scope, we not only pollute the scope with more functionality, we also put program logic from the controller to the partial. And we shouldn’t do that! A partial should be as easy as possible and all application logic should be in the controller or services. But this is also a trade-off, as this solution might be fine for small and simple problems.

Best regards,
Thomas

Testing AngularJS directives with Jasmine

Directives

AngularJS provides a mechanism called directives. Directives are markers in our HTML which Angular will read and use to inject some special behavior to our HTML code. As this sounds a little bit theoretically, let’s look at an example:

In this example the directive ng-model is used which will bind the value of the input field to a field called name in the current $scope. This directive already comes with AngularJS, but it’s also possible to write your own directive. That’s what we do right now.

A custom directive

In order to have an useful example to test, we write our own directive. In this case we will use a directive which will listen for an “on-enter-event” on an element. It looks like that:

And you use it like that:

The example creates a directive called onEnter which you must refer as on-enter in your HTML. The directive takes a single argument which is a function in the current scope (e.g.: showNotification()). So when we type in your input field and press enter the directive will be called. It will get an event and it will check if the event comes from “enter” or another key. If it was an “enter”, the directive will call our method. Looks good? So let’s test it.

Testing

Testing this directive isn’t a big thing, but it will bring us the evidence that it works like we expect it. A Jasmine test might look like this:

What does the test do?

The test does the following: First we load the module which contains our directive and inject AngularJS’ $rootScope and $compile service. As a directive is attached to the HTML, we need to take some HTML and compile it with AngularJS in order to make the directive work like in a real life scenario.

Now we create our actual test case. First we create a spy function (jasmine.createSpy('test');) and attach it to our scope (which is simply the root scope). This function should be called by the directive if it works correctly. Now we create some HTML which uses the directive and compile it. The last thing we need to do is to create an on-enter-event and fire it up on the compiled element. This simulates the user pressing enter.

Last but not least we verify that the on-enter directive worked and has invoked our test function on the root scope.

What the test doesn’t do

The test only verifies the happy path. It tests if the function is called when enter is pressed, but it doesn’t verify the opposite: Is the directive only listening on “enter” or will it also call our function if another key is pressed? However, implementing this test shouldn’t be a big thing now.

Best regards,
Thomas

More

https://docs.angularjs.org/guide/directive

A mocked Spring security configuration for testing

Spring security is great! It gives you the possibility to secure your app and to create a login with a few simple lines of code. However, it could also become annoying during development, when you have to log yourself in again and again. So why not create a mocked Spring authentication for development and testing?

Create a new profile to active the mock

Before we implement the actual mock, we first create a new profile to active or deactive it. Spring profiles give you the opportunity to decide which bean Spring should use when starting your app. This means you can say “Hey Spring! Use my mock!” or “Hey Spring! Use my production implementation!”. Let’s call our profile “SECURITY_MOCK”. First, we add the profile to our production security configuration, so that we can switch it off and use the mock instead. Note that this is the only change we need to do to our already existing code!

Now we create our mock configuration:

Using a profile like shown above, we can decide which implementation Spring will use. We just need to pass the profile to our application properties:

A mocked authentication provider

Now that we have defined a profile to switch our mock on and off, we need to do the actual implementation. The first thing we do, is to write a mocked authentication provider. Spring will use this authentication provider to check the user, validate its password and to return the user details. The authentication provider depends on our own implementation, but it might look like that:

A couple of things are important right here:

  • Use the SECURITY_MOCK profile again and annotate the class with @Primary so it will replace any other bean when using the mock profile!
  • As I’m pretty sure you want to use a custom user class, set it to the details!

The mocked security config

After you implemented the mocked authentication provider, the actual security config will be very easy. The only thing you need to do is to use your authentication provider:

Usage

After you implemented both, the mocked security config and the authentication provider mock, the usage is straight forward. You just activate the profile (in your application properties) and then you can use the authenticated user in our code:

Best regards,
Thomas

Gradle’s bootRun and Window’s command length limit

Sometimes Gradle’s bootRun and Window’s command length limit are two opponents. If you use bootRun to start your Spring Boot app from Gradle all class path dependencies will be added to the start command. Gradle will run something like this in the end:

That’s fine and will work for a really long time. But as longer you work on your project you will add more and more dependencies. And it might happen that you cross a secret line of no return: 32767. That’s the number of characters which Windows’ CreateProcess function will accept. Any additional character will cause an exception:

Sh*t! So how to start your app? With Gradle, you can use a simple work around: Instead of appending all your dependencies to the start command, you create a JAR file with a manifest file. This manifest file contains all dependencies and will be the only dependency in your start command:

In Gradle code, this looks like this:

The pathingJar task creates a JAR file with a manifest file containing all our dependencies. This file will become pretty big, but that’s totally fine. Now we only extend the bootRun task to use this pathing JAR. This will solve the problem.

Best regards,
Thomas

More

Resizing Vagrant box disk space

Vagrant is a great tool to provision virtual machines! As I’m a passionated Windows user, Vagrant is the weapon of my choice whenever I need to use some Linux-only tools such as Docker. I spinn up a new Linux VM, already configured with the things I need and start working. However, when it comes to resizing a disk, Vagrant is not nice to you…

The problem

Vagrant doesn’t provide any out-of-the-box option to configure or to change the disk size. The disk size of a VM totally depends on the base image used for the VM. There are base images with a 10 GB disk, some with a 20 GB disk and some other with a 40 GB disk. There is no Vagrant option to change this – and even worse: most Vagrant boxes use VMDK disks which cannot be resized!

Resizing (manually) with VirtualBox

As Vagrant doesn’t provide any out-of-the-box functionality, we need to do the resizing “manually”. Of course, we can write a script for this, too, but for now we keep it simple and do it by hand.

  1. First we need to convert the VMDK disk to a VDI disk which can be resized. We do this with the VBoxManage tool which comes with the VirtualBox installation:
  2. Now we can easily resize this VDI disk, e.g. to 50 GB:
  3. The last step we need to do is just to use the new disk instead of the old one. We can do this by cloning the VDI disk back to the original VMDK disk or within a view clicks in VirtualBox:

    2016-01-06 16_32_02-Oracle VM VirtualBox Manager

That’s it! Now start your VM with vagrant up and check the disk space. It’s at 50 GB and we have new free space again!

Best regards,
Thomas

More

Anti Pattern: Don’t use Optionals for data repositories

Java 8 Optionals

Java 8 introduced a new feature call Optionals. Optionals are an easy way to force the caller of a method to deal with a possible null return value:

If you use an Optional as the return type of your method, whoever calls the method will be reminded that it might return null. If you use Optionals, you don’t need to think about NotFoundExceptions, special return types or JavaDoc comments which state that the method might return null. An Optional says more than a thousand comments!

Optionals might just postpone the problem

But an Optional doesn’t do one thing: it doesn’t answer the question what to do if there is no method result. It just postpones the problem to the caller. This might be OK if null is a quite expected result of the method, but in most cases null means something went wrong. Don’t postpone this!

An example

Nearly every application stores data. Whenever data is stored, it will be loaded again which might go wrong as the data simply couldn’t be found. That sounds like a good use case for Optionals! Let’s see how it could look like:

Nice! If there is no Person with the given ID the repository will return an empty Optional and the caller has to deal with it. Technically, this is a nice and clean solution. But from the business perspective it isn’t. The real question is: Can it happen that we look for an ID which is not present? If yes, than an Optional is a good solution, but I would doubt that in many case.

Whenever you attempt to load data by its ID, it must be present! There are hardly any cases where you guess or search for an ID. Such IDs are like references or pointers in a programming language: they must point to something and returning an ID which points to nothing is a very bad idea. A typical situation where you load data by its ID goes like this: You provide a list of data (maybe a result of a search) and you provide a detail view on a single entry. So, you show the list in your UI and on a click on of the elements, the details of ID XYZ-123 are shown. This set of data must be there! Don’t use an optional here!

Never return null

Back in the days (which means before Java 8), there was a rule which said that you shall never return null. This rule was always a bit tricky to follow as it might lead to a lot of hidden traps. People started to return empty objects, special objects, return codes and other crazy stuff. If you did this in the past and you are using Optionals now, you definitely improved! But you should still ask you, why there might be no result and if it is OK to have no result. Not only from a technical perspective but also from the business perspective.

Optional is just a new name for null.

When to use Optionals

The actual use case for Optionals is functional programming in Java 8. If you use this, you will filter, map or reduce data and you will often come to the point where there might be the possibility that no data exists. It’s a good idea to use Optionals here, as you often write this code in a fluent style. A null pointer is really ugly to handle here. But the main difference is another: You do a search or filtering which perfectly could have no result. This is the main point for using an Optional. Don’t use an Optional, because you don’t want to deal with null (you need to do it anyway later!), use it because you have a really good reason to return null.

Best regards,
Thomas

Create random test objects with Java reflection

Although Java is an object oriented language, you will often separate our data and your actual business logic. You will write POJOs, entities, domain models and DTOs which you will pass to services, repositories and controllers. If you do so, you will properly need test data for those objects. Often, the data you pass will be very important as it represents the state of your application and business process. You must design it carefully to get the test results you are looking for. However, there are also some cases where the data isn’t so important – it must just be there! You need an object, filled with random data. That’s it.

Java’s reflection mechanism offers an easy method to create POJOs filled with random data. Here is a basic code snippet which will take a class, instantiate it and fills its fields with random data. Maybe it makes your test setup easier.

Best regards,
Thomas

Two-way binding for URL parameters in AngularJS

Single page applications (maybe with AngularJS?) are the new cool kid in town. So are URL parameters which are an essential part of how single page applications work. URL parameters hold the current state of an application and enable to open the application in this state (e.g. with a so called deep link). That’s how the look like:

In this example, showAll=true and filterByName=Thomas are the URL parameters. The hash (#) divides the URL into two parts: a part which goes to the server (before #) and a part which stays on the client (behind #). This is the so called anchor part which holds our URL parameters. So this part of the URL is purely for our AngularJS client!

Two way binding

Two way binding means that bind a parameter of our URL (e.g. filterByName) to a parameter of the controller (let’s say it has the same name: myController.filterByName). To achieve this, we need update our controller if the URL parameter changes and we need to update our URL parameter if the controller changes. That’s what two way mean – controller to URL, URL to controller.

Controller >> URL

Let’s start with the first way: controller to URL. Everytime a property of the controller changes, we want to update the corresponding property of the URL. To do this, we use Angular’s $watch method (see https://docs.angularjs.org/api/ng/type/$rootScope.Scope). The method $watch allows to watch a value and do something if it changes. Exactly what we want! The code is pretty straight forward:

This code will do the following: It will create a watcher which listens on the property filterByName of our controller. If the property changes, we get the new value and set it to the URL (by $location.search("filterByName", newVal);).

(By the way: To use the URL parameters we use a service called $location provided by Angular! That’s the default way to access the URL.)

URL >> controller

Now we only need the way back: URL to controller. As you might guess, we just use another watcher for that. But in this case we use Angular’s $on. This looks like that:

What $on does is simple: It listens for events, e.g. the $locationChangeSuccess event, which is thrown after the URL has changed. If this happens, we use the $location service to read the value from the URL and assign it to our controller.

Put it to a method!

We already have achieved what we wanted: we have a two way binding between our controller and the URL. One last thing we might do right now, is to put this into a nice method we can reuse:

If the property of our controller changes (e.g. because the use inputs data) the URL will change. And if the URL changes (e.g. because we clicked on a link) the controller will change. We have a two way binding between controller and URL!

Best regards,
Thomas

Links

Using Spring Data for database views without an ID

A database view is a great way to prepare complicated data structures right in the database and present it in a more convenient way. We usually use database views to map our technical driven database structure (with a lot of tables and foreign keys) to a more business driven structure. This means that we might join tables, concatenate values or just rename the columns, because a particular name suits better to the current business context.

To map those views to Java entities, we simply use Spring data:

However, the example above wouldn’t work. Spring would complain that the @Id annotation is missing and would throw a org.hibernate.AnnotationException: No identifier specified for entity exception.

From a business perspective, this is bad. The id of a company is its company id, the id of a person is its person id. But both are missing in the view, which has not unique identifier.

We could solve this problem by a simple trick: we invent an unique identifier – our current row number!

We can now use the row number in our Spring Data entity:

Best regards,
Thomas