Cleanup your JUnit Tests by using Contexts

Anyone familiar with Ruby Specs knows, that using a context to structure your unit tests helps to keep your tests clean and readable, while it also reduces the number of boilerplate setup code tremendously.

After watching episode 20 of Uncle Bob’s CleanCoders screencast, I found myself disappointed about the missing context ability of JUnit’s default test runner. Also Uncle Bob came up with a workaround of creating contexts by using inner static classes and inheritance (this is all the default runner supports), I felt like this was wrong and also, that it should be possible to come up with a test runner that supports something like the Ruby Specs Contexts.

So, the last two days I spent some time on working on such a test runner and I’ve just finished a first early alpha. Let’s see what the test code looks like, after applying the runner to the main class. For this example, I reformatted the tests provided by the BankTests class of Uncle Bob’s screencast:

package de.bechte.junit.samples.context;

import de.bechte.junit.runners.context.HierarchicalContextRunner;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertEquals;

@RunWith(HierarchicalContextRunner.class)
public class BankTests {
    @BeforeClass
    public static void beforeClassFirstLevel() throws Exception {
        // Silly, just for demonstration, that before class works for the main class
        System.out.println("Setup Database, etc...");
    }

    @AfterClass
    public static void afterClassFirstLevel() throws Exception {
        // Silly, just for demonstration, that after class works for the main class
        System.out.println("Cleanup Database, etc...");
    }

    private static final double MONEY_DELTA = .00001;

    private static void assertMoneyEquals(double expected, double actual) {
        assertEquals(expected, actual, MONEY_DELTA);
    }

    public class BankContext {
        @Before
        public void setCurrentInterestRate() {
            Bank.currentInterestRate = 2.75;
        }

        @Test
        public void interestRateIsSet() {
            // Rather stupid test, but it shows, that tests
            // on this level get also executed smoothly...
            assertMoneyEquals(2.75, Bank.currentInterestRate);
        }

        public class NewAccountContext {
            private Account newAccount;

            @Before
            public void createNewAccount() throws Exception {
                newAccount = new Account();
            }

            @Test
            public void balanceIsZero() throws Exception {
                assertMoneyEquals(0.0, newAccount.getBalance());
            }

            @Test
            public void interestRateIsSet() throws Exception {
                assertMoneyEquals(2.75, newAccount.getInterestRate());
            }
        }

        public class OldAccountContext {
            private Account oldAccount;

            @Before
            public void createOldAccount() throws Exception {
                oldAccount = new Account();
            }

            public class AfterInterestRateChangeContext {
                @Before
                public void changeInterestRate() {
                    Bank.currentInterestRate = 3.25;
                }

                @Test
                public void shouldHaveOldInterestRate() throws Exception {
                    assertMoneyEquals(2.75, oldAccount.getInterestRate());
                }

                @Test
                public void failingTest() throws Exception {
                    assertMoneyEquals(1.0, Bank.currentInterestRate);
                }

                @Test
                @Ignore
                public void ignoredTest() throws Exception {
                    // whatever
                }
            }
        }
    }
}

Results running this test with IntelliJ:

After I added the two ignored and failing tests, the result changes to:

The implementation is now available as an add-on to JUnit 4.11, hosted on github and available from the Maven Central Repository. You will find more information on the wiki on github.

Please give it a try and post as much feedback as possible. :)

Tagged with:  

Multiple Constrained Shortest Path Calculation

Finally, I finished writing on my master thesis. The topic of the thesis is “Algorithms for Optimizing operative Flight Dispatching”. Flight dispatching is the process of route planning for a flight with the focus on optimizing a variety of economic factors such as fuel consumption, flight duration, flyover costs, etc. The optimization underlies certain constraints, reaching from the maximum fuel capacity of the aircraft to complex airway usage policies. The aim is to find an optimal airway that holds for all constraints and minimizes the use of resources.

The problem is modelled as a directed graph, such that waypoints are the graph’s nodes, paths between waypoints are the graph’s edges, and the resources consumed by taking an edge are the graph’s edge weights. Certain conditions such as weather, flight level, the weight of the aircraft, and other time-dependent constraints require the evaluation of the edge weights at relaxation time which makes the graph highly dynamic and tremendously increases calculation time.

To reconcile this increase it is common to perform the calculation on a smaller subgraph, where nodes unlikely to be part of a good solution are trimmed from the graph. Moreover, the calculation is split into a horizontal and a vertical phase. The horizontal phase operates on a two-dimensional grid of waypoints given by their longitude and latitude only, whereas the vertical phase optimizes the flight level of the airway found in the horizontal phase.

The thesis introduces a new framework that provides high performance calculations and a modular, flexible design that is easy to maintain and extend. The framework was mainly built for analyzing optimization algorithms for flight dispatching but is easily adaptable for other optimization scenarios that operate on dynamic or static graphs.

Concerning flight dispatching, the thesis also evaluates an alternative approach that is based on linear programming. With this approach it is possible to precalculate upper and lower boundaries for the resource consumptions which can be used for a graph reduction. The Benchmarks of the Framework show that this graph reduction has advantages over the common geometric cut-of and can be used to form an algorithm that operates on the three-dimensional structure, combining the horizontal and vertical phase and thus leading to better results. Finally, an overview of the results is given and interesting questions for further research are pointed out.

For all interested in reading the thesis, it is available for download. Also, the framework can be downloaded and used for running the benchmarks and tests locally.

I appreciate your feedback anytime.

Tagged with:  

Mac OS X Unified Buffer Cache

Mac OS X speedups the startup of programs by keeping the memory used by that program as long as it is not necessarily needed by any other program. This is also called the inactive memory, which you can easily see when opening Activity Monitor. There will always be some inactive memory around, at least if you have just closed a program like Mail.

At first, inactive memory is nothing bad. I like my programs to startup real quick, especially as I normally do not restart my iMac for weeks or months. But with Lion and Mountain Lion, Apple changed something in the kernel leading to extensive swapping when processing “large” files (when the file size extends the amount of free memory).

The reason for this is the Unified Buffer Cache. This cache is used for reading/writing files. The files are loaded into memory and can be access very fast instead of reading/writing from disk every time. With the newest release this Unified Buffer Cache is allowed to be swapped to disk: That’s the swapping that occurs when large files are processed!

But why would somebody swap file buffer cache when reading/writing the swapped cache becomes even more expensive than simply reading/writing from/to the disk? Nobody knows, but Apple activated it and now we have to deal with it, until they finally fix it!

What can we do? As a programmer you can easily disable the UBC before accessing huge files (like movies for encoding, etc.) by calling the file control method:


fcntl(fd, F_GLOBAL_NOCACHE, 1);

(see also: http://wagerlabs.com/blog/2008/03/04/hacking-the-mac-osx-unified-buffer-cache/)

For all non-developers out there, I wrote a little console tool that will exactly do the same. You can disable and enable the UBC for certain files by a single command:


$ ./UBCUtil file1 file2 file3 ... (disables UBC)
$ ./UBCUtil -reset file1 file2 file3 ... (enables UBC)

Source Code is also available within the ZIP file. Enjoy.

Download UBCUtil

Page 1 of 1112345...10...Last »

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

© 2009-2010 Stefan Bechtold