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. 

No comments:

Post a Comment