Skip to content

Tag: static

JUnit and static fields

I’m sure you’ve seen this pattern of using static fields to maintain application state:

public class AppState {

    static MovieRepository movieRepository;
    static StarRepository starRepository;

    static {
        AppState.movieRepository = new MovieRepository();
        AppState.starRepository = new StarRepository();
    }
}

One reason this is a bad idea is it can cause inconsistent test results. If one test modifies the application state and then a second test runs, the second test will use the first test’s state.