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:
-
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$Providerin theMETA-INF/servicesfolder inside your Unit Test source folder. That file should contain the fully qualified class name of your ownLookup.Providerimplementation. In my case the file contain just the stringcom.rubenlaguna.en4j.searchlucene.NoteFinderLuceneImplTestbecause the test class itself implementsLookup.Provider.By adding this to
META-INF/servicesyou’re actually forcingLookup.getLookup()to use yourLookup.Providerto obtain theLookupinstance that will be returned -
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.