Showing posts with label test. Show all posts
Showing posts with label test. Show all posts

Friday, August 28, 2015

Integration tests in SpringBoot without external dependencies

Target - test all layers of SpringBoot REST application in isolation from external components.

Complexity - typical application uses database and makes calls to remote services.

Solutions:

a) Use spring-test support for integration tests. It actually starts whole app for you on random port. At the same time, all components of app can be wired into test for additional manipulations.

b) Use RestAssured to make calls to our application

c) Use RestTemplate to make remote calls and MockServer from spring-test to mock them

d) Use in-memory database. HSQLDB does the simulating job pretty well.

e) Use separate Spring profile to tweak app configuration


Here is a small example putting it all together:


Thursday, February 13, 2014

Restricting system resource access in JUnit tests - SecurityManager

JUnit is not the best framework for integration tests, but it definitely is the most popular one. Today I'm going to describe one weird integration test, where you have to make sure that code under test does not write anything to file system o_O.

Why? Well, for example you application runs in cloud, where quite often file system is not available. Probably you should not go paranoid about making such test for your own code base, but external libraries might give you quite unpleasant surprise. They will work fine on your machine and will crash as soon as you deploy them to sand boxed environment.

Which library can require such test? Basically, any library can attempt to store temp file, for example. Offcourse, good libraries won't do that, but sometimes you don't have any choice.

Java Security has lot's of interesting stuff that many Java developers don't use in their everyday job. One of them is SecurityManager. SecurityManager is responsible for controlling system resource access. One example of SecurityManager in action is that Java applets can't access files on client  machine. Looks like we need something similar for our integration test.


This solution uses JUnit rules for better portability across tests. General idea is that you configure SecurityManager before test run with custom SecurityManager. After test you remove that SecurityManager. Custom implementation throws SecurityException when  code tries to write to file.

Besides checking file writes, SecurityManager can check many other system resources. Network connections for example.