Ruben Laguna’s blog

JUnit and Netbeans. Injecting in Objects in the Default Lookup

If you need to unit test classes in a netbeans module and the classes use the Lookup.getDefault() to “lookup” things that you want to mock you probably wonder how you can place the mock objects in the default Lookup

Adding objects to the Netbeans’s default Lookup is relatively simple. Here is the answer:


  1. Replace the Lookup instance returned by the Lookup.getDefault()
    by defining a new entry in META-INF/services.

    It’s just a matter of adding a file named org.openide.util.Lookup$Provider in the META-INF/services folder inside your Unit Test source folder. That file should contain the fully qualified class name of your own Lookup.Provider implementation.
    In my case the file contain just the string com.rubenlaguna.en4j.searchlucene.NoteFinderLuceneImplTest because the test class itself implements Lookup.Provider.

    By adding this to META-INF/services you’re actually forcing Lookup.getLookup() to use your Lookup.Provider to obtain the Lookup instance that will be returned

  2. Create you own Lookup.Provider. You can even let your test class implement Lookup.Provider if you only have one test class.

    In this example you can see that I inject a NoteRepository.class into the default lookup.

You can see a living example here

Comments